feat: add smart auto-albums with visual workflow editor

- Visual node-based workflow editor using React Flow
- Asset triggers: new asset, asset updated, all assets (with lookback buffer)
- Logic nodes: if/switch with combinable conditions (person, location, date, camera, EXIF, favorites, album membership)
- Action nodes: create album, add/remove from album, favorite, unfavorite, archive, tag
- Workflow-level triggers: manual run, cron schedule, webhook
- Debug mode: dry run with step-by-step logs and asset previews
- Run history with per-node asset tracking
- Run detail page with annotated read-only graph
- Processed asset tracking to prevent duplicate processing
- Multi-person picker with face thumbnails
- Album picker dropdown for actions
- JSON import/export for workflow sharing
- Workflow list page with create, delete, enable/disable
This commit is contained in:
Varun committed 2026-04-07 19:20:43 +05:30
1 parent e814793190
commit c7a7ea3023
41 files changed
+4756 -2

No files matched your search

+73
View File
@@ -0,0 +1,73 @@
import { FilePlus, FileEdit, Database, GitBranch, GitFork, FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag } from "lucide-react";
interface PaletteItem {
type: string;
subType: string;
label: string;
icon: any;
color: string;
}
const assetTriggerItems: PaletteItem[] = [
{ type: "trigger", subType: "new_asset", label: "New Asset", icon: FilePlus, color: "text-green-500" },
{ type: "trigger", subType: "asset_updated", label: "Asset Updated", icon: FileEdit, color: "text-green-500" },
{ type: "trigger", subType: "all_assets", label: "All Assets", icon: Database, color: "text-green-500" },
];
const logicItems: PaletteItem[] = [
{ type: "logic_if", subType: "if", label: "If", icon: GitBranch, color: "text-yellow-500" },
{ type: "logic_switch", subType: "switch", label: "Switch", icon: GitFork, color: "text-orange-500" },
];
const actionItems: PaletteItem[] = [
{ type: "action", subType: "create_album", label: "Create Album", icon: FolderPlus, color: "text-purple-500" },
{ type: "action", subType: "add_to_album", label: "Add to Album", icon: FolderInput, color: "text-purple-500" },
{ type: "action", subType: "remove_from_album", label: "Remove from Album", icon: FolderMinus, color: "text-purple-500" },
{ type: "action", subType: "favorite", label: "Favorite", icon: Heart, color: "text-purple-500" },
{ type: "action", subType: "unfavorite", label: "Unfavorite", icon: HeartOff, color: "text-purple-500" },
{ type: "action", subType: "archive", label: "Archive", icon: Archive, color: "text-purple-500" },
{ type: "action", subType: "tag", label: "Add Tag", icon: Tag, color: "text-purple-500" },
];
function PaletteGroup({ title, items }: { title: string; items: PaletteItem[] }) {
const onDragStart = (event: React.DragEvent, item: PaletteItem) => {
event.dataTransfer.setData("application/reactflow", JSON.stringify({
type: item.type,
subType: item.subType,
}));
event.dataTransfer.effectAllowed = "move";
};
return (
<div className="mb-4">
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-1">{title}</h3>
<div className="space-y-1">
{items.map((item) => {
const Icon = item.icon;
return (
<div
key={`${item.type}-${item.subType}`}
draggable
onDragStart={(e) => onDragStart(e, item)}
className="flex items-center gap-2 px-2 py-1.5 rounded cursor-grab active:cursor-grabbing hover:bg-muted transition-colors"
>
<Icon className={`h-3.5 w-3.5 ${item.color}`} />
<span className="text-xs text-foreground">{item.label}</span>
</div>
);
})}
</div>
</div>
);
}
export default function NodePalette() {
return (
<div className="w-48 border-r bg-background p-3 overflow-y-auto">
<h2 className="text-sm font-semibold mb-3">Nodes</h2>
<PaletteGroup title="Asset Triggers" items={assetTriggerItems} />
<PaletteGroup title="Logic" items={logicItems} />
<PaletteGroup title="Actions" items={actionItems} />
</div>
);
}
@@ -0,0 +1,134 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { Check } from "lucide-react";
import { cn } from "@/lib/utils";
import { listAlbums } from "@/handlers/api/album.handler";
import { IAlbum } from "@/types/album";
import { useEffect, useState } from "react";
interface ActionConfigProps {
subType: string;
config: any;
onChange: (config: any) => void;
}
const templateVars = ["{city}", "{date}", "{person}", "{camera}", "{state}", "{country}"];
function AlbumPicker({ value, onChange }: { value: string | undefined; onChange: (albumId: string, albumName: string) => void }) {
const [open, setOpen] = useState(false);
const [albums, setAlbums] = useState<IAlbum[]>([]);
const [loading, setLoading] = useState(false);
const [selectedAlbum, setSelectedAlbum] = useState<IAlbum | null>(null);
useEffect(() => {
setLoading(true);
listAlbums()
.then((data) => {
setAlbums(data);
if (value) {
const found = data.find((a: IAlbum) => a.id === value);
if (found) setSelectedAlbum(found);
}
})
.finally(() => setLoading(false));
}, []);
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button type="button" className="flex items-center gap-2 h-8 px-3 w-full border rounded text-sm bg-background hover:bg-muted transition-colors text-left">
{selectedAlbum ? (
<span className="truncate">{selectedAlbum.albumName}</span>
) : (
<span className="text-muted-foreground">Select album...</span>
)}
</button>
</PopoverTrigger>
<PopoverContent className="w-64 p-0 z-[10000]" align="start">
<Command>
<CommandInput placeholder="Search albums..." className="text-xs" />
<CommandList>
<CommandEmpty>{loading ? "Loading..." : "No albums found."}</CommandEmpty>
<CommandGroup>
{albums.map((album) => (
<CommandItem
key={album.id}
value={album.albumName}
onSelect={() => {
setSelectedAlbum(album);
onChange(album.id, album.albumName);
setOpen(false);
}}
className="flex items-center gap-2"
>
<span className="text-xs truncate flex-1">{album.albumName}</span>
<Check className={cn("h-3 w-3", value === album.id ? "opacity-100" : "opacity-0")} />
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
}
export default function ActionConfig({ subType, config, onChange }: ActionConfigProps) {
if (subType === "create_album") {
return (
<div className="space-y-2">
<Label className="text-xs">Album Name Template</Label>
<Input
className="h-8 text-sm"
placeholder="Trip to {city} - {date}"
value={config.nameTemplate || ""}
onChange={(e) => onChange({ ...config, nameTemplate: e.target.value })}
/>
<div className="flex flex-wrap gap-1">
{templateVars.map((v) => (
<Badge
key={v}
variant="outline"
className="text-[10px] cursor-pointer hover:bg-muted"
onClick={() => onChange({ ...config, nameTemplate: (config.nameTemplate || "") + v })}
>
{v}
</Badge>
))}
</div>
</div>
);
}
if (subType === "add_to_album" || subType === "remove_from_album") {
return (
<div className="space-y-2">
<Label className="text-xs">Album</Label>
<AlbumPicker
value={config.albumId}
onChange={(albumId, albumName) => onChange({ ...config, albumId, albumName })}
/>
</div>
);
}
if (subType === "tag") {
return (
<div className="space-y-2">
<Label className="text-xs">Tag Name</Label>
<Input
className="h-8 text-sm"
placeholder="e.g. Vacation"
value={config.tagName || ""}
onChange={(e) => onChange({ ...config, tagName: e.target.value })}
/>
</div>
);
}
// favorite, unfavorite, archive — no config needed
return <p className="text-xs text-muted-foreground">No configuration needed.</p>;
}
@@ -0,0 +1,319 @@
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList } from "@/components/ui/command";
import { ICondition, ConditionType } from "@/types/workflow";
import { Plus, X, Check } from "lucide-react";
import { listPeople } from "@/handlers/api/people.handler";
import { IPerson } from "@/types/person";
import { PERSON_THUBNAIL_PATH } from "@/config/routes";
import { useEffect, useState } from "react";
import { cn } from "@/lib/utils";
const conditionTypeLabels: Record<ConditionType, string> = {
person: "Person",
person_unnamed: "Unnamed People",
city: "City",
state: "State",
country: "Country",
geo_radius: "Geo Radius",
date_range: "Date Range",
date_relative: "Relative Date",
day_of_week: "Day of Week",
camera_make: "Camera Make",
camera_model: "Camera Model",
lens: "Lens",
asset_type: "Asset Type",
iso_range: "ISO Range",
focal_length: "Focal Length",
rating: "Rating",
is_favorited: "Favorited",
not_in_album: "Not in Any Album",
not_in_specific_album: "Not in Specific Album",
};
const conditionTypes = Object.keys(conditionTypeLabels) as ConditionType[];
interface PersonPickerProps {
selectedIds: string[];
onChange: (personIds: string[], personNames: string[]) => void;
}
function PersonPicker({ selectedIds, onChange }: PersonPickerProps) {
const [open, setOpen] = useState(false);
const [people, setPeople] = useState<IPerson[]>([]);
const [loading, setLoading] = useState(false);
useEffect(() => {
setLoading(true);
listPeople({ page: 1, perPage: 500, sort: "createdAt", sortOrder: "desc", visibility: "visible", type: "named" })
.then((res) => setPeople(res.people))
.finally(() => setLoading(false));
}, []);
const selectedSet = new Set(selectedIds || []);
const selectedPeople = people.filter((p) => selectedSet.has(p.id));
const togglePerson = (person: IPerson) => {
let nextIds: string[];
let nextNames: string[];
if (selectedSet.has(person.id)) {
nextIds = selectedIds.filter((id) => id !== person.id);
nextNames = selectedPeople.filter((p) => p.id !== person.id).map((p) => p.name);
} else {
nextIds = [...selectedIds, person.id];
nextNames = [...selectedPeople.map((p) => p.name), person.name];
}
onChange(nextIds, nextNames);
};
return (
<div className="space-y-2">
{/* Selected people chips */}
{selectedPeople.length > 0 && (
<div className="flex flex-wrap gap-1">
{selectedPeople.map((p) => (
<button
key={p.id}
type="button"
onClick={() => togglePerson(p)}
className="flex items-center gap-1 px-1.5 py-0.5 rounded-full bg-muted hover:bg-destructive/10 transition-colors group"
>
<img src={PERSON_THUBNAIL_PATH(p.id)} alt="" className="h-4 w-4 rounded-full object-cover" />
<span className="text-[10px] font-medium">{p.name || "Unknown"}</span>
<X className="h-2.5 w-2.5 text-muted-foreground group-hover:text-destructive" />
</button>
))}
</div>
)}
{/* Picker */}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<button type="button" className="flex items-center gap-2 h-7 px-2 w-full border rounded text-xs bg-background hover:bg-muted transition-colors">
<span className="text-muted-foreground">
{selectedIds.length === 0 ? "Select people..." : "Add more..."}
</span>
</button>
</PopoverTrigger>
<PopoverContent className="w-56 p-0 z-[10000]" align="start">
<Command>
<CommandInput placeholder="Search people..." className="text-xs" />
<CommandList>
<CommandEmpty>{loading ? "Loading..." : "No people found."}</CommandEmpty>
<CommandGroup>
{people.map((person) => (
<CommandItem
key={person.id}
value={person.name || person.id}
onSelect={() => togglePerson(person)}
className="flex items-center gap-2"
>
<img src={PERSON_THUBNAIL_PATH(person.id)} alt="" className="h-6 w-6 rounded-full object-cover" />
<span className="text-xs truncate flex-1">{person.name || "Unknown"}</span>
<Check className={cn("h-3 w-3", selectedSet.has(person.id) ? "opacity-100" : "opacity-0")} />
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
);
}
interface ConditionEditorProps {
conditions: ICondition[];
onChange: (conditions: ICondition[]) => void;
}
function ConditionFields({ condition, onChange }: { condition: ICondition; onChange: (c: ICondition) => void }) {
switch (condition.type) {
case "city":
case "state":
case "country":
return (
<div className="flex gap-2">
<Select value={condition.match || "equals"} onValueChange={(v) => onChange({ ...condition, match: v })}>
<SelectTrigger className="h-7 text-xs w-24"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="equals">Equals</SelectItem>
<SelectItem value="not_equals">Not Equals</SelectItem>
</SelectContent>
</Select>
<Input className="h-7 text-xs" placeholder={condition.type} value={condition[condition.type] || ""} onChange={(e) => onChange({ ...condition, [condition.type]: e.target.value })} />
</div>
);
case "camera_make":
return <Input className="h-7 text-xs" placeholder="e.g. Apple" value={condition.make || ""} onChange={(e) => onChange({ ...condition, make: e.target.value })} />;
case "camera_model":
return <Input className="h-7 text-xs" placeholder="e.g. iPhone 16 Pro" value={condition.model || ""} onChange={(e) => onChange({ ...condition, model: e.target.value })} />;
case "lens":
return <Input className="h-7 text-xs" placeholder="Lens model" value={condition.lensModel || ""} onChange={(e) => onChange({ ...condition, lensModel: e.target.value })} />;
case "asset_type":
return (
<Select value={condition.assetType || "IMAGE"} onValueChange={(v) => onChange({ ...condition, assetType: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="IMAGE">Image</SelectItem>
<SelectItem value="VIDEO">Video</SelectItem>
</SelectContent>
</Select>
);
case "date_range":
return (
<div className="flex gap-2">
<Input className="h-7 text-xs" type="date" value={condition.after || ""} onChange={(e) => onChange({ ...condition, after: e.target.value })} />
<Input className="h-7 text-xs" type="date" value={condition.before || ""} onChange={(e) => onChange({ ...condition, before: e.target.value })} />
</div>
);
case "date_relative":
return (
<div className="flex items-center gap-1">
<span className="text-xs text-muted-foreground">Last</span>
<Input className="h-7 text-xs w-16" type="number" min={1} value={condition.lastDays || ""} onChange={(e) => onChange({ ...condition, lastDays: parseInt(e.target.value) || 0 })} />
<span className="text-xs text-muted-foreground">days</span>
</div>
);
case "iso_range":
case "focal_length":
return (
<div className="flex gap-2">
<Input className="h-7 text-xs" type="number" placeholder="Min" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: parseFloat(e.target.value) || undefined })} />
<Input className="h-7 text-xs" type="number" placeholder="Max" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: parseFloat(e.target.value) || undefined })} />
</div>
);
case "rating":
return (
<div className="flex gap-2">
<Input className="h-7 text-xs w-16" type="number" min={1} max={5} placeholder="Min" value={condition.min ?? ""} onChange={(e) => onChange({ ...condition, min: parseInt(e.target.value) || undefined })} />
<Input className="h-7 text-xs w-16" type="number" min={1} max={5} placeholder="Max" value={condition.max ?? ""} onChange={(e) => onChange({ ...condition, max: parseInt(e.target.value) || undefined })} />
</div>
);
case "is_favorited":
return (
<Select value={condition.value === false ? "false" : "true"} onValueChange={(v) => onChange({ ...condition, value: v === "true" })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="true">Is Favorited</SelectItem>
<SelectItem value="false">Not Favorited</SelectItem>
</SelectContent>
</Select>
);
case "person":
return (
<div className="space-y-2">
<Select value={condition.match || "contains_any"} onValueChange={(v) => onChange({ ...condition, match: v })}>
<SelectTrigger className="h-7 text-xs"><SelectValue /></SelectTrigger>
<SelectContent>
<SelectItem value="contains_any">Contains any of</SelectItem>
<SelectItem value="contains_all">Contains all of</SelectItem>
<SelectItem value="not_contains">Does not contain</SelectItem>
</SelectContent>
</Select>
<PersonPicker
selectedIds={condition.personIds || (condition.personId ? [condition.personId] : [])}
onChange={(personIds, personNames) => onChange({ ...condition, personIds, personNames })}
/>
</div>
);
case "geo_radius":
return (
<div className="space-y-1">
<div className="flex gap-2">
<Input className="h-7 text-xs" type="number" step="any" placeholder="Latitude" value={condition.lat ?? ""} onChange={(e) => onChange({ ...condition, lat: parseFloat(e.target.value) || 0 })} />
<Input className="h-7 text-xs" type="number" step="any" placeholder="Longitude" value={condition.lng ?? ""} onChange={(e) => onChange({ ...condition, lng: parseFloat(e.target.value) || 0 })} />
</div>
<div className="flex items-center gap-1">
<Input className="h-7 text-xs w-20" type="number" min={1} placeholder="Radius" value={condition.radiusKm ?? ""} onChange={(e) => onChange({ ...condition, radiusKm: parseFloat(e.target.value) || 0 })} />
<span className="text-xs text-muted-foreground">km</span>
</div>
</div>
);
case "day_of_week":
return (
<div className="flex gap-1 flex-wrap">
{["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"].map((day, i) => {
const days: number[] = condition.days || [];
const active = days.includes(i);
return (
<button
key={day}
type="button"
className={`text-[10px] px-1.5 py-0.5 rounded border ${active ? "bg-primary text-primary-foreground" : "bg-muted text-muted-foreground"}`}
onClick={() => {
const next = active ? days.filter((d: number) => d !== i) : [...days, i];
onChange({ ...condition, days: next });
}}
>
{day}
</button>
);
})}
</div>
);
case "not_in_album":
case "person_unnamed":
return null;
case "not_in_specific_album":
return <Input className="h-7 text-xs" placeholder="Album ID" value={condition.albumId || ""} onChange={(e) => onChange({ ...condition, albumId: e.target.value })} />;
default:
return null;
}
}
export default function ConditionEditor({ conditions, onChange }: ConditionEditorProps) {
const addCondition = () => {
onChange([...conditions, { type: "city" }]);
};
const removeCondition = (index: number) => {
onChange(conditions.filter((_, i) => i !== index));
};
const updateCondition = (index: number, condition: ICondition) => {
const next = [...conditions];
next[index] = condition;
onChange(next);
};
const changeType = (index: number, type: ConditionType) => {
const next = [...conditions];
next[index] = { type };
onChange(next);
};
return (
<div className="space-y-2">
{conditions.map((condition, i) => (
<div key={i} className="p-2 border rounded space-y-2 bg-muted/30">
<div className="flex items-center gap-1">
<Select value={condition.type} onValueChange={(v) => changeType(i, v as ConditionType)}>
<SelectTrigger className="h-7 text-xs flex-1"><SelectValue /></SelectTrigger>
<SelectContent>
{conditionTypes.map((t) => (
<SelectItem key={t} value={t}>{conditionTypeLabels[t]}</SelectItem>
))}
</SelectContent>
</Select>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => removeCondition(i)}>
<X className="h-3 w-3" />
</Button>
</div>
<ConditionFields condition={condition} onChange={(c) => updateCondition(i, c)} />
{i < conditions.length - 1 && (
<div className="text-center">
<span className="text-[10px] font-medium text-muted-foreground bg-muted px-2 py-0.5 rounded">AND</span>
</div>
)}
</div>
))}
<Button variant="outline" size="sm" className="w-full h-7 text-xs" onClick={addCondition}>
<Plus className="h-3 w-3 mr-1" />
Add Condition
</Button>
</div>
);
}
@@ -0,0 +1,23 @@
import { ICondition } from "@/types/workflow";
import ConditionEditor from "./ConditionEditor";
import { Label } from "@/components/ui/label";
interface IfConfigProps {
config: { conditions?: ICondition[] };
onChange: (config: any) => void;
}
export default function IfConfig({ config, onChange }: IfConfigProps) {
return (
<div className="space-y-3">
<div>
<Label className="text-xs">Conditions (AND)</Label>
<p className="text-[10px] text-muted-foreground mb-2">All conditions must match for the TRUE branch.</p>
</div>
<ConditionEditor
conditions={config.conditions || []}
onChange={(conditions) => onChange({ ...config, conditions })}
/>
</div>
);
}
@@ -0,0 +1,71 @@
import { ICondition } from "@/types/workflow";
import ConditionEditor from "./ConditionEditor";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Plus, X } from "lucide-react";
interface SwitchCase {
label: string;
conditions: ICondition[];
handle: string;
}
interface SwitchConfigProps {
config: { cases?: SwitchCase[] };
onChange: (config: any) => void;
}
export default function SwitchConfig({ config, onChange }: SwitchConfigProps) {
const cases = config.cases || [];
const addCase = () => {
const handle = `case_${cases.length}`;
onChange({
...config,
cases: [...cases, { label: `Case ${cases.length + 1}`, conditions: [], handle }],
});
};
const removeCase = (index: number) => {
onChange({ ...config, cases: cases.filter((_: any, i: number) => i !== index) });
};
const updateCase = (index: number, updates: Partial<SwitchCase>) => {
const next = [...cases];
next[index] = { ...next[index], ...updates };
onChange({ ...config, cases: next });
};
return (
<div className="space-y-3">
<div>
<Label className="text-xs">Cases</Label>
<p className="text-[10px] text-muted-foreground mb-2">First matching case wins. Non-matching assets go to Default.</p>
</div>
{cases.map((c: SwitchCase, i: number) => (
<div key={c.handle} className="border rounded p-2 space-y-2">
<div className="flex items-center gap-1">
<Input
className="h-7 text-xs flex-1"
value={c.label}
onChange={(e) => updateCase(i, { label: e.target.value })}
placeholder="Case label"
/>
<Button variant="ghost" size="sm" className="h-7 w-7 p-0" onClick={() => removeCase(i)}>
<X className="h-3 w-3" />
</Button>
</div>
<ConditionEditor
conditions={c.conditions}
onChange={(conditions) => updateCase(i, { conditions })}
/>
</div>
))}
<Button variant="outline" size="sm" className="w-full h-7 text-xs" onClick={addCase}>
<Plus className="h-3 w-3 mr-1" />
Add Case
</Button>
</div>
);
}
@@ -0,0 +1,49 @@
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface TriggerConfigProps {
subType: string;
config: any;
onChange: (config: any) => void;
webhookToken?: string | null;
}
export default function TriggerConfig({ subType, config, onChange, webhookToken }: TriggerConfigProps) {
if (subType === "manual") {
return <p className="text-xs text-muted-foreground">No configuration needed. Use the Run button to trigger manually.</p>;
}
if (subType === "schedule") {
return (
<div className="space-y-2">
<Label className="text-xs">Cron Expression</Label>
<Input
className="h-8 text-sm font-mono"
placeholder="0 */6 * * *"
value={config.cron || ""}
onChange={(e) => onChange({ ...config, cron: e.target.value })}
/>
<p className="text-[10px] text-muted-foreground">
Examples: <code>0 */6 * * *</code> (every 6h), <code>0 9 * * 1</code> (Mon 9am)
</p>
</div>
);
}
if (subType === "webhook") {
const url = webhookToken ? `${window.location.origin}/api/webhooks/${webhookToken}` : "Save workflow first";
return (
<div className="space-y-2">
<Label className="text-xs">Webhook URL</Label>
<div className="flex gap-1">
<Input className="h-8 text-xs font-mono" readOnly value={url} />
</div>
<p className="text-[10px] text-muted-foreground">
Configure this URL in Immich admin webhook settings.
</p>
</div>
);
}
return null;
}
+4
View File
@@ -0,0 +1,4 @@
export { default as ConditionEditor } from "./ConditionEditor";
export { default as IfConfig } from "./IfConfig";
export { default as SwitchConfig } from "./SwitchConfig";
export { default as ActionConfig } from "./ActionConfig";
@@ -0,0 +1,49 @@
import { Handle, Position, NodeProps } from "@xyflow/react";
import { FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag } from "lucide-react";
const actionIcons: Record<string, any> = {
create_album: FolderPlus,
add_to_album: FolderInput,
remove_from_album: FolderMinus,
favorite: Heart,
unfavorite: HeartOff,
archive: Archive,
tag: Tag,
};
const actionLabels: Record<string, string> = {
create_album: "Create Album",
add_to_album: "Add to Album",
remove_from_album: "Remove from Album",
favorite: "Favorite",
unfavorite: "Unfavorite",
archive: "Archive",
tag: "Add Tag",
};
export default function ActionNode({ data, selected }: NodeProps) {
const subType = data.subType as string || "create_album";
const Icon = actionIcons[subType] || FolderPlus;
const label = actionLabels[subType] || "Action";
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[180px] ${selected ? "border-blue-500" : "border-purple-500"}`}>
<Handle type="target" position={Position.Top} className="!bg-purple-500 !w-3 !h-3" />
<div className="flex items-center gap-2">
<div className="p-1.5 rounded bg-purple-500/10">
<Icon className="h-4 w-4 text-purple-500" />
</div>
<div>
<p className="text-xs font-medium text-foreground">{label}</p>
{subType === "create_album" && config.nameTemplate && (
<p className="text-[10px] text-muted-foreground truncate max-w-[140px]">{config.nameTemplate}</p>
)}
{subType === "tag" && config.tagName && (
<p className="text-[10px] text-muted-foreground">{config.tagName}</p>
)}
</div>
</div>
</div>
);
}
+40
View File
@@ -0,0 +1,40 @@
import { Handle, Position, NodeProps } from "@xyflow/react";
import { GitBranch } from "lucide-react";
export default function IfNode({ data, selected }: NodeProps) {
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
const conditions = config.conditions || [];
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[200px] ${selected ? "border-blue-500" : "border-yellow-500"}`}>
<Handle type="target" position={Position.Top} className="!bg-yellow-500 !w-3 !h-3" />
<div className="flex items-center gap-2 mb-2">
<div className="p-1.5 rounded bg-yellow-500/10">
<GitBranch className="h-4 w-4 text-yellow-500" />
</div>
<p className="text-xs font-medium text-foreground">IF</p>
</div>
{conditions.length > 0 ? (
<div className="space-y-1">
{conditions.map((c: any, i: number) => (
<p key={i} className="text-[10px] text-muted-foreground truncate">
{c.type}{c.city ? `: ${c.city}` : ""}{c.personId ? " (person)" : ""}{c.value !== undefined ? `: ${c.value}` : ""}
</p>
))}
</div>
) : (
<p className="text-[10px] text-muted-foreground">No conditions set</p>
)}
<div className="flex justify-between mt-3 px-2">
<div className="flex flex-col items-center">
<span className="text-[9px] text-green-500 font-medium">TRUE</span>
<Handle type="source" position={Position.Bottom} id="true" className="!bg-green-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
</div>
<div className="flex flex-col items-center">
<span className="text-[9px] text-red-500 font-medium">FALSE</span>
<Handle type="source" position={Position.Bottom} id="false" className="!bg-red-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
</div>
</div>
</div>
);
}
@@ -0,0 +1,41 @@
import { Handle, Position, NodeProps } from "@xyflow/react";
import { GitFork } from "lucide-react";
export default function SwitchNode({ data, selected }: NodeProps) {
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
const cases = config.cases || [];
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[220px] ${selected ? "border-blue-500" : "border-orange-500"}`}>
<Handle type="target" position={Position.Top} className="!bg-orange-500 !w-3 !h-3" />
<div className="flex items-center gap-2 mb-2">
<div className="p-1.5 rounded bg-orange-500/10">
<GitFork className="h-4 w-4 text-orange-500" />
</div>
<p className="text-xs font-medium text-foreground">SWITCH</p>
<span className="text-[10px] text-muted-foreground ml-auto">{cases.length} cases</span>
</div>
{cases.length > 0 && (
<div className="space-y-1 mb-2">
{cases.map((c: any, i: number) => (
<p key={i} className="text-[10px] text-muted-foreground truncate">
{c.label || `Case ${i + 1}`}
</p>
))}
</div>
)}
<div className="flex justify-between mt-3 px-1 gap-2">
{cases.map((c: any, i: number) => (
<div key={c.handle || `case_${i}`} className="flex flex-col items-center">
<span className="text-[9px] text-orange-500 font-medium truncate max-w-[50px]">{c.label || `C${i + 1}`}</span>
<Handle type="source" position={Position.Bottom} id={c.handle || `case_${i}`} className="!bg-orange-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
</div>
))}
<div className="flex flex-col items-center">
<span className="text-[9px] text-muted-foreground font-medium">DEF</span>
<Handle type="source" position={Position.Bottom} id="default" className="!bg-gray-400 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0 !mt-1" />
</div>
</div>
</div>
);
}
@@ -0,0 +1,47 @@
import { Handle, Position, NodeProps } from "@xyflow/react";
import { FilePlus, FileEdit, Database } from "lucide-react";
const triggerIcons: Record<string, any> = {
new_asset: FilePlus,
asset_updated: FileEdit,
all_assets: Database,
};
const triggerLabels: Record<string, string> = {
new_asset: "New Asset",
asset_updated: "Asset Updated",
all_assets: "All Assets",
};
const triggerDescriptions: Record<string, string> = {
new_asset: "Since last run (or workflow creation)",
asset_updated: "Since last run (or workflow creation)",
all_assets: "Full library scan",
};
export default function TriggerNode({ data, selected }: NodeProps) {
const subType = data.subType as string || "new_asset";
const Icon = triggerIcons[subType] || FilePlus;
const label = triggerLabels[subType] || "Asset Trigger";
const description = triggerDescriptions[subType] || "";
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
const lookbackMin = config.lookbackMinutes;
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[180px] ${selected ? "border-blue-500" : "border-green-500"}`}>
<div className="flex items-center gap-2">
<div className="p-1.5 rounded bg-green-500/10">
<Icon className="h-4 w-4 text-green-500" />
</div>
<div>
<p className="text-xs font-medium text-foreground">{label}</p>
<p className="text-[10px] text-muted-foreground">
{description}
{lookbackMin && subType !== "all_assets" ? ` + ${lookbackMin}m buffer` : ""}
</p>
</div>
</div>
<Handle type="source" position={Position.Bottom} className="!bg-green-500 !w-3 !h-3" />
</div>
);
}
+11
View File
@@ -0,0 +1,11 @@
import TriggerNode from "./TriggerNode";
import IfNode from "./IfNode";
import SwitchNode from "./SwitchNode";
import ActionNode from "./ActionNode";
export const nodeTypes = {
trigger: TriggerNode,
logic_if: IfNode,
logic_switch: SwitchNode,
action: ActionNode,
};
+6 -1
View File
@@ -1,4 +1,4 @@
import { Copy, GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, PackageSearch, Rewind, Search, Settings, Share2, User, Video } from "lucide-react";
import { Copy, GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, PackageSearch, Rewind, Search, Settings, Share2, User, Video, Workflow } from "lucide-react";
export const sidebarNavs = [
// {
@@ -59,6 +59,11 @@ export const sidebarNavs = [
link: "/assets/bulk-duplicate-finder",
icon: <Copy className="h-4 w-4" />,
},
{
title: "Workflows",
link: "/workflows",
icon: <Workflow className="h-4 w-4" />,
},
{
title: "Orphan Finder",
link: "/assets/orphan-finder",
+14 -1
View File
@@ -102,4 +102,17 @@ export const VALIDATE_PERMISSIONS_PATH = BASE_API_ENDPOINT + "/validate-permissi
// Import Jobs (queue)
export const IMPORT_JOBS_PATH = BASE_API_ENDPOINT + "/import-jobs";
export const IMPORT_JOB_PATH = (jobId: string) => BASE_API_ENDPOINT + "/import-jobs/" + jobId;
export const IMPORT_JOB_PATH = (jobId: string) => BASE_API_ENDPOINT + "/import-jobs/" + jobId;
// Workflows
export const LIST_WORKFLOWS_PATH = BASE_API_ENDPOINT + "/workflows";
export const CREATE_WORKFLOW_PATH = BASE_API_ENDPOINT + "/workflows";
export const GET_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
export const UPDATE_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
export const DELETE_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id;
export const SAVE_WORKFLOW_GRAPH_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/graph";
export const RUN_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/run";
export const WORKFLOW_RUNS_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/runs";
export const EXPORT_WORKFLOW_PATH = (id: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/export";
export const IMPORT_WORKFLOW_PATH = BASE_API_ENDPOINT + "/workflows/import";
export const WORKFLOW_RUN_DETAIL_PATH = (id: string, runId: string) => BASE_API_ENDPOINT + "/workflows/" + id + "/runs/" + runId;
+50
View File
@@ -0,0 +1,50 @@
CREATE TABLE `workflow_edges` (
`id` text PRIMARY KEY NOT NULL,
`workflow_id` text NOT NULL,
`source_node_id` text NOT NULL,
`target_node_id` text NOT NULL,
`source_handle` text,
`created_at` integer,
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`source_node_id`) REFERENCES `workflow_nodes`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`target_node_id`) REFERENCES `workflow_nodes`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `workflow_nodes` (
`id` text PRIMARY KEY NOT NULL,
`workflow_id` text NOT NULL,
`type` text NOT NULL,
`sub_type` text NOT NULL,
`data` text DEFAULT '{}' NOT NULL,
`position_x` real DEFAULT 0 NOT NULL,
`position_y` real DEFAULT 0 NOT NULL,
`created_at` integer,
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `workflow_runs` (
`id` text PRIMARY KEY NOT NULL,
`workflow_id` text NOT NULL,
`trigger` text NOT NULL,
`status` text DEFAULT 'running' NOT NULL,
`result` text DEFAULT '{}',
`error` text,
`started_at` integer,
`completed_at` integer,
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade
);
--> statement-breakpoint
CREATE TABLE `workflows` (
`id` text PRIMARY KEY NOT NULL,
`owner_id` text NOT NULL,
`name` text NOT NULL,
`description` text,
`enabled` integer DEFAULT false NOT NULL,
`cron_schedule` text,
`webhook_token` text,
`viewport` text DEFAULT '{"x":0,"y":0,"zoom":1}' NOT NULL,
`created_at` integer,
`updated_at` integer
);
--> statement-breakpoint
CREATE UNIQUE INDEX `workflows_webhook_token_unique` ON `workflows` (`webhook_token`);
@@ -0,0 +1,9 @@
CREATE TABLE `workflow_processed_assets` (
`id` text PRIMARY KEY NOT NULL,
`workflow_id` text NOT NULL,
`asset_id` text NOT NULL,
`run_id` text NOT NULL,
`processed_at` integer,
FOREIGN KEY (`workflow_id`) REFERENCES `workflows`(`id`) ON UPDATE no action ON DELETE cascade,
FOREIGN KEY (`run_id`) REFERENCES `workflow_runs`(`id`) ON UPDATE no action ON DELETE cascade
);
+661
View File
@@ -0,0 +1,661 @@
{
"version": "6",
"dialect": "sqlite",
"id": "fcc0b754-0e0f-4a14-9375-0fce84bf107f",
"prevId": "bec76260-a0eb-4895-a32e-244df56b6c2e",
"tables": {
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"api_keys": {
"name": "api_keys",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"key_name": {
"name": "key_name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"secret": {
"name": "secret",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"immich_key_id": {
"name": "immich_key_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"api_keys_user_id_purpose_unique": {
"name": "api_keys_user_id_purpose_unique",
"columns": [
"user_id",
"purpose"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"import_job_items": {
"name": "import_job_items",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"asset_id": {
"name": "asset_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"item_data": {
"name": "item_data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"immich_id": {
"name": "immich_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error": {
"name": "error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"import_job_items_job_id_import_jobs_id_fk": {
"name": "import_job_items_job_id_import_jobs_id_fk",
"tableFrom": "import_job_items",
"tableTo": "import_jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"import_jobs": {
"name": "import_jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"platform": {
"name": "platform",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"url_config": {
"name": "url_config",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"import_data": {
"name": "import_data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"total_count": {
"name": "total_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"uploaded_count": {
"name": "uploaded_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"skipped_count": {
"name": "skipped_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"failed_count": {
"name": "failed_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_edges": {
"name": "workflow_edges",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"source_node_id": {
"name": "source_node_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_node_id": {
"name": "target_node_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"source_handle": {
"name": "source_handle",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_edges_workflow_id_workflows_id_fk": {
"name": "workflow_edges_workflow_id_workflows_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"workflow_edges_source_node_id_workflow_nodes_id_fk": {
"name": "workflow_edges_source_node_id_workflow_nodes_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflow_nodes",
"columnsFrom": [
"source_node_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"workflow_edges_target_node_id_workflow_nodes_id_fk": {
"name": "workflow_edges_target_node_id_workflow_nodes_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflow_nodes",
"columnsFrom": [
"target_node_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_nodes": {
"name": "workflow_nodes",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sub_type": {
"name": "sub_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"data": {
"name": "data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"position_x": {
"name": "position_x",
"type": "real",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"position_y": {
"name": "position_y",
"type": "real",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_nodes_workflow_id_workflows_id_fk": {
"name": "workflow_nodes_workflow_id_workflows_id_fk",
"tableFrom": "workflow_nodes",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_runs": {
"name": "workflow_runs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"trigger": {
"name": "trigger",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'running'"
},
"result": {
"name": "result",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'{}'"
},
"error": {
"name": "error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"completed_at": {
"name": "completed_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_runs_workflow_id_workflows_id_fk": {
"name": "workflow_runs_workflow_id_workflows_id_fk",
"tableFrom": "workflow_runs",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflows": {
"name": "workflows",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"owner_id": {
"name": "owner_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"enabled": {
"name": "enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"cron_schedule": {
"name": "cron_schedule",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"webhook_token": {
"name": "webhook_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"viewport": {
"name": "viewport",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{\"x\":0,\"y\":0,\"zoom\":1}'"
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"workflows_webhook_token_unique": {
"name": "workflows_webhook_token_unique",
"columns": [
"webhook_token"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+733
View File
@@ -0,0 +1,733 @@
{
"version": "6",
"dialect": "sqlite",
"id": "f760ba33-ed15-4972-8578-51644001b8ed",
"prevId": "fcc0b754-0e0f-4a14-9375-0fce84bf107f",
"tables": {
"settings": {
"name": "settings",
"columns": {
"key": {
"name": "key",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"value": {
"name": "value",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"api_keys": {
"name": "api_keys",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"purpose": {
"name": "purpose",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"key_name": {
"name": "key_name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"secret": {
"name": "secret",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"immich_key_id": {
"name": "immich_key_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"api_keys_user_id_purpose_unique": {
"name": "api_keys_user_id_purpose_unique",
"columns": [
"user_id",
"purpose"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"import_job_items": {
"name": "import_job_items",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"job_id": {
"name": "job_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"asset_id": {
"name": "asset_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"item_data": {
"name": "item_data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"immich_id": {
"name": "immich_id",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"error": {
"name": "error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"import_job_items_job_id_import_jobs_id_fk": {
"name": "import_job_items_job_id_import_jobs_id_fk",
"tableFrom": "import_job_items",
"tableTo": "import_jobs",
"columnsFrom": [
"job_id"
],
"columnsTo": [
"id"
],
"onDelete": "no action",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"import_jobs": {
"name": "import_jobs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"user_id": {
"name": "user_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"platform": {
"name": "platform",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'pending'"
},
"url": {
"name": "url",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"url_config": {
"name": "url_config",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"import_data": {
"name": "import_data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"total_count": {
"name": "total_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"uploaded_count": {
"name": "uploaded_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"skipped_count": {
"name": "skipped_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"failed_count": {
"name": "failed_count",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_edges": {
"name": "workflow_edges",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"source_node_id": {
"name": "source_node_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"target_node_id": {
"name": "target_node_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"source_handle": {
"name": "source_handle",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_edges_workflow_id_workflows_id_fk": {
"name": "workflow_edges_workflow_id_workflows_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"workflow_edges_source_node_id_workflow_nodes_id_fk": {
"name": "workflow_edges_source_node_id_workflow_nodes_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflow_nodes",
"columnsFrom": [
"source_node_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"workflow_edges_target_node_id_workflow_nodes_id_fk": {
"name": "workflow_edges_target_node_id_workflow_nodes_id_fk",
"tableFrom": "workflow_edges",
"tableTo": "workflow_nodes",
"columnsFrom": [
"target_node_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_nodes": {
"name": "workflow_nodes",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"type": {
"name": "type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"sub_type": {
"name": "sub_type",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"data": {
"name": "data",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{}'"
},
"position_x": {
"name": "position_x",
"type": "real",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"position_y": {
"name": "position_y",
"type": "real",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": 0
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_nodes_workflow_id_workflows_id_fk": {
"name": "workflow_nodes_workflow_id_workflows_id_fk",
"tableFrom": "workflow_nodes",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_processed_assets": {
"name": "workflow_processed_assets",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"asset_id": {
"name": "asset_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"run_id": {
"name": "run_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"processed_at": {
"name": "processed_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_processed_assets_workflow_id_workflows_id_fk": {
"name": "workflow_processed_assets_workflow_id_workflows_id_fk",
"tableFrom": "workflow_processed_assets",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
},
"workflow_processed_assets_run_id_workflow_runs_id_fk": {
"name": "workflow_processed_assets_run_id_workflow_runs_id_fk",
"tableFrom": "workflow_processed_assets",
"tableTo": "workflow_runs",
"columnsFrom": [
"run_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflow_runs": {
"name": "workflow_runs",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"workflow_id": {
"name": "workflow_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"trigger": {
"name": "trigger",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"status": {
"name": "status",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'running'"
},
"result": {
"name": "result",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false,
"default": "'{}'"
},
"error": {
"name": "error",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"started_at": {
"name": "started_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"completed_at": {
"name": "completed_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {},
"foreignKeys": {
"workflow_runs_workflow_id_workflows_id_fk": {
"name": "workflow_runs_workflow_id_workflows_id_fk",
"tableFrom": "workflow_runs",
"tableTo": "workflows",
"columnsFrom": [
"workflow_id"
],
"columnsTo": [
"id"
],
"onDelete": "cascade",
"onUpdate": "no action"
}
},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
},
"workflows": {
"name": "workflows",
"columns": {
"id": {
"name": "id",
"type": "text",
"primaryKey": true,
"notNull": true,
"autoincrement": false
},
"owner_id": {
"name": "owner_id",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"name": {
"name": "name",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false
},
"description": {
"name": "description",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"enabled": {
"name": "enabled",
"type": "integer",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": false
},
"cron_schedule": {
"name": "cron_schedule",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"webhook_token": {
"name": "webhook_token",
"type": "text",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"viewport": {
"name": "viewport",
"type": "text",
"primaryKey": false,
"notNull": true,
"autoincrement": false,
"default": "'{\"x\":0,\"y\":0,\"zoom\":1}'"
},
"created_at": {
"name": "created_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
},
"updated_at": {
"name": "updated_at",
"type": "integer",
"primaryKey": false,
"notNull": false,
"autoincrement": false
}
},
"indexes": {
"workflows_webhook_token_unique": {
"name": "workflows_webhook_token_unique",
"columns": [
"webhook_token"
],
"isUnique": true
}
},
"foreignKeys": {},
"compositePrimaryKeys": {},
"uniqueConstraints": {},
"checkConstraints": {}
}
},
"views": {},
"enums": {},
"_meta": {
"schemas": {},
"tables": {},
"columns": {}
},
"internal": {
"indexes": {}
}
}
+14
View File
@@ -15,6 +15,20 @@
"when": 1775227109706,
"tag": "0001_rainy_jamie_braddock",
"breakpoints": true
},
{
"idx": 2,
"version": "6",
"when": 1775560183481,
"tag": "0002_thin_triton",
"breakpoints": true
},
{
"idx": 3,
"version": "6",
"when": 1775567654903,
"tag": "0003_spooky_lockheed",
"breakpoints": true
}
]
}
+1
View File
@@ -1,3 +1,4 @@
export * from "./settings.schema";
export * from "./apiKeys.schema";
export * from "./importJobs.schema";
export * from "./workflows.schema";
+56
View File
@@ -0,0 +1,56 @@
import { sqliteTable, text, integer, real } from "drizzle-orm/sqlite-core";
import { randomUUID } from "crypto";
export const workflows = sqliteTable("workflows", {
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
ownerId: text("owner_id").notNull(),
name: text("name").notNull(),
description: text("description"),
enabled: integer("enabled", { mode: "boolean" }).notNull().default(false),
cronSchedule: text("cron_schedule"),
webhookToken: text("webhook_token").unique(),
viewport: text("viewport").notNull().default('{"x":0,"y":0,"zoom":1}'),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
updatedAt: integer("updated_at", { mode: "timestamp" })
.$defaultFn(() => new Date())
.$onUpdate(() => new Date()),
});
export const workflowNodes = sqliteTable("workflow_nodes", {
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
type: text("type").notNull(),
subType: text("sub_type").notNull(),
data: text("data").notNull().default("{}"),
positionX: real("position_x").notNull().default(0),
positionY: real("position_y").notNull().default(0),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
});
export const workflowEdges = sqliteTable("workflow_edges", {
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
sourceNodeId: text("source_node_id").notNull().references(() => workflowNodes.id, { onDelete: "cascade" }),
targetNodeId: text("target_node_id").notNull().references(() => workflowNodes.id, { onDelete: "cascade" }),
sourceHandle: text("source_handle"),
createdAt: integer("created_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
});
export const workflowRuns = sqliteTable("workflow_runs", {
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
trigger: text("trigger").notNull(),
status: text("status").notNull().default("running"),
result: text("result").default("{}"),
error: text("error"),
startedAt: integer("started_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
completedAt: integer("completed_at", { mode: "timestamp" }),
});
export const workflowProcessedAssets = sqliteTable("workflow_processed_assets", {
id: text("id").primaryKey().$defaultFn(() => randomUUID()),
workflowId: text("workflow_id").notNull().references(() => workflows.id, { onDelete: "cascade" }),
assetId: text("asset_id").notNull(),
runId: text("run_id").notNull().references(() => workflowRuns.id, { onDelete: "cascade" }),
processedAt: integer("processed_at", { mode: "timestamp" }).$defaultFn(() => new Date()),
});
+57
View File
@@ -0,0 +1,57 @@
import {
LIST_WORKFLOWS_PATH,
CREATE_WORKFLOW_PATH,
GET_WORKFLOW_PATH,
UPDATE_WORKFLOW_PATH,
DELETE_WORKFLOW_PATH,
SAVE_WORKFLOW_GRAPH_PATH,
RUN_WORKFLOW_PATH,
WORKFLOW_RUNS_PATH,
EXPORT_WORKFLOW_PATH,
IMPORT_WORKFLOW_PATH,
} from "@/config/routes";
import API from "@/lib/api";
import { IWorkflow, IWorkflowWithDetails, IWorkflowRun, IWorkflowExport } from "@/types/workflow";
export const listWorkflows = async (): Promise<IWorkflow[]> => {
return API.get(LIST_WORKFLOWS_PATH);
};
export const createWorkflow = async (data: { name: string; description?: string }): Promise<IWorkflow> => {
return API.post(CREATE_WORKFLOW_PATH, data);
};
export const getWorkflow = async (id: string): Promise<IWorkflowWithDetails> => {
return API.get(GET_WORKFLOW_PATH(id));
};
export const updateWorkflow = async (id: string, data: Partial<IWorkflow>): Promise<IWorkflow> => {
return API.put(UPDATE_WORKFLOW_PATH(id), data);
};
export const deleteWorkflow = async (id: string): Promise<void> => {
return API.delete(DELETE_WORKFLOW_PATH(id));
};
export const saveWorkflowGraph = async (
id: string,
data: { nodes: any[]; edges: any[]; viewport?: any }
): Promise<void> => {
return API.put(SAVE_WORKFLOW_GRAPH_PATH(id), data);
};
export const runWorkflow = async (id: string, mode?: "manual" | "debug"): Promise<IWorkflowRun> => {
return API.post(RUN_WORKFLOW_PATH(id), { mode });
};
export const getWorkflowRuns = async (id: string): Promise<IWorkflowRun[]> => {
return API.get(WORKFLOW_RUNS_PATH(id));
};
export const exportWorkflow = async (id: string): Promise<IWorkflowExport> => {
return API.get(EXPORT_WORKFLOW_PATH(id));
};
export const importWorkflow = async (data: IWorkflowExport): Promise<IWorkflow> => {
return API.post(IMPORT_WORKFLOW_PATH, data);
};
+168
View File
@@ -0,0 +1,168 @@
import { ENV } from "@/config/environment";
import { db } from "@/config/db";
import { exif } from "@/schema";
import { assets } from "@/schema/assets.schema";
import { person } from "@/schema/person.schema";
import { assetFaces } from "@/schema/assetFaces.schema";
import { eq, inArray, sql, desc } from "drizzle-orm";
import { IUser } from "@/types/user";
import { getUserHeaders } from "@/helpers/user.helper";
interface ActionResult {
action: string;
assetsProcessed: number;
albumId?: string;
albumName?: string;
error?: string;
}
async function immichFetch(path: string, method: string, body: any, user: IUser): Promise<any> {
const res = await fetch(`${ENV.IMMICH_URL}/api${path}`, {
method,
headers: {
...getUserHeaders(user),
"Content-Type": "application/json",
},
body: body ? JSON.stringify(body) : undefined,
});
if (!res.ok) {
const text = await res.text();
throw new Error(`Immich API error ${res.status}: ${text}`);
}
const contentType = res.headers.get("content-type");
if (contentType?.includes("application/json")) {
return res.json();
}
return null;
}
async function resolveTemplate(template: string, assetIds: string[]): Promise<string> {
if (!template || assetIds.length === 0) return template;
let result = template;
if (result.includes("{city}") || result.includes("{state}") || result.includes("{country}") || result.includes("{camera}")) {
// Get most common EXIF values
const exifRows = await db
.select({
city: exif.city,
state: exif.state,
country: exif.country,
make: exif.make,
model: exif.model,
})
.from(exif)
.where(inArray(exif.assetId, assetIds))
.limit(100);
const mostCommon = (values: (string | null)[]) => {
const counts = new Map<string, number>();
for (const v of values) {
if (v) counts.set(v, (counts.get(v) || 0) + 1);
}
let best = "";
let bestCount = 0;
for (const [v, c] of counts) {
if (c > bestCount) { best = v; bestCount = c; }
}
return best || "Unknown";
};
result = result.replace("{city}", mostCommon(exifRows.map((r) => r.city)));
result = result.replace("{state}", mostCommon(exifRows.map((r) => r.state)));
result = result.replace("{country}", mostCommon(exifRows.map((r) => r.country)));
result = result.replace("{camera}", mostCommon(exifRows.map((r) => [r.make, r.model].filter(Boolean).join(" "))));
}
if (result.includes("{date}")) {
const today = new Date();
result = result.replace("{date}", today.toISOString().split("T")[0]);
}
if (result.includes("{person}")) {
const faces = await db
.select({ name: person.name })
.from(assetFaces)
.innerJoin(person, eq(assetFaces.personId, person.id))
.where(inArray(assetFaces.assetId, assetIds))
.limit(100);
const names = faces.map((f) => f.name).filter(Boolean);
const mostCommon = (values: string[]) => {
const counts = new Map<string, number>();
for (const v of values) counts.set(v, (counts.get(v) || 0) + 1);
let best = "";
let bestCount = 0;
for (const [v, c] of counts) {
if (c > bestCount) { best = v; bestCount = c; }
}
return best || "Unknown";
};
result = result.replace("{person}", mostCommon(names));
}
return result;
}
export async function executeAction(
subType: string,
config: any,
assetIds: string[],
user: IUser
): Promise<ActionResult> {
if (assetIds.length === 0) {
return { action: subType, assetsProcessed: 0 };
}
switch (subType) {
case "create_album": {
const albumName = await resolveTemplate(config.nameTemplate || "Auto Album", assetIds);
const album = await immichFetch("/albums", "POST", { albumName, assetIds }, user);
return { action: "create_album", assetsProcessed: assetIds.length, albumId: album.id, albumName };
}
case "add_to_album": {
if (!config.albumId) throw new Error("Album ID is required for add_to_album");
await immichFetch(`/albums/${config.albumId}/assets`, "PUT", { ids: assetIds }, user);
return { action: "add_to_album", assetsProcessed: assetIds.length, albumId: config.albumId };
}
case "remove_from_album": {
if (!config.albumId) throw new Error("Album ID is required for remove_from_album");
await immichFetch(`/albums/${config.albumId}/assets`, "DELETE", { ids: assetIds }, user);
return { action: "remove_from_album", assetsProcessed: assetIds.length, albumId: config.albumId };
}
case "favorite": {
await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: true }, user);
return { action: "favorite", assetsProcessed: assetIds.length };
}
case "unfavorite": {
await immichFetch("/assets", "PUT", { ids: assetIds, isFavorite: false }, user);
return { action: "unfavorite", assetsProcessed: assetIds.length };
}
case "archive": {
await immichFetch("/assets", "PUT", { ids: assetIds, isArchived: true }, user);
return { action: "archive", assetsProcessed: assetIds.length };
}
case "tag": {
if (!config.tagName) throw new Error("Tag name is required");
// Tags API may vary by Immich version — try the standard approach
try {
// Create or get tag
const tag = await immichFetch("/tags", "POST", { name: config.tagName, type: "OBJECT" }, user);
// Tag assets
await immichFetch(`/tags/${tag.id}/assets`, "PUT", { ids: assetIds }, user);
return { action: "tag", assetsProcessed: assetIds.length };
} catch (e: any) {
return { action: "tag", assetsProcessed: 0, error: e.message };
}
}
default:
return { action: subType, assetsProcessed: 0, error: `Unknown action: ${subType}` };
}
}
+149
View File
@@ -0,0 +1,149 @@
import { SQL, and, eq, ne, gte, lte, isNull, sql } from "drizzle-orm";
import { assets } from "@/schema/assets.schema";
import { exif } from "@/schema";
import { ICondition } from "@/types/workflow";
import { subDays } from "date-fns";
export function buildConditions(conditions: ICondition[], ownerId: string): SQL[] {
const clauses: SQL[] = [
eq(assets.ownerId, ownerId),
eq(assets.visibility, "timeline"),
eq(assets.status, "active"),
isNull(assets.deletedAt),
];
for (const c of conditions) {
const clause = buildSingleCondition(c);
if (clause) clauses.push(clause);
}
return clauses;
}
function buildSingleCondition(c: ICondition): SQL | undefined {
switch (c.type) {
case "city":
return c.match === "not_equals"
? ne(exif.city, c.city)
: eq(exif.city, c.city);
case "state":
return c.match === "not_equals"
? ne(exif.state, c.state)
: eq(exif.state, c.state);
case "country":
return c.match === "not_equals"
? ne(exif.country, c.country)
: eq(exif.country, c.country);
case "camera_make":
return eq(exif.make, c.make);
case "camera_model":
return eq(exif.model, c.model);
case "lens":
return eq(exif.lensModel, c.lensModel);
case "asset_type":
return eq(assets.type, c.assetType || "IMAGE");
case "is_favorited":
return eq(assets.isFavorite, c.value !== false);
case "date_range": {
const parts: SQL[] = [];
if (c.after) parts.push(gte(exif.dateTimeOriginal, new Date(c.after)));
if (c.before) parts.push(lte(exif.dateTimeOriginal, new Date(c.before)));
return parts.length > 0 ? and(...parts)! : undefined;
}
case "date_relative":
if (c.lastDays) {
return gte(exif.dateTimeOriginal, subDays(new Date(), c.lastDays));
}
return undefined;
case "day_of_week":
if (c.days && c.days.length > 0) {
return sql`EXTRACT(DOW FROM ${exif.dateTimeOriginal}) IN (${sql.raw(c.days.join(","))})`;
}
return undefined;
case "iso_range": {
const parts: SQL[] = [];
if (c.min !== undefined) parts.push(gte(exif.iso, c.min));
if (c.max !== undefined) parts.push(lte(exif.iso, c.max));
return parts.length > 0 ? and(...parts)! : undefined;
}
case "focal_length": {
const parts: SQL[] = [];
if (c.min !== undefined) parts.push(gte(exif.focalLength, c.min));
if (c.max !== undefined) parts.push(lte(exif.focalLength, c.max));
return parts.length > 0 ? and(...parts)! : undefined;
}
case "rating": {
const parts: SQL[] = [];
if (c.min !== undefined) parts.push(gte(exif.rating, c.min));
if (c.max !== undefined) parts.push(lte(exif.rating, c.max));
return parts.length > 0 ? and(...parts)! : undefined;
}
case "person": {
const ids: string[] = c.personIds || (c.personId ? [c.personId] : []);
if (ids.length === 0) return undefined;
if (c.match === "not_contains") {
// Asset must not contain ANY of these people
const checks = ids.map((pid: string) =>
sql`NOT EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" = ${pid})`
);
return and(...checks)!;
}
if (c.match === "contains_all") {
// Asset must contain ALL of these people
const checks = ids.map((pid: string) =>
sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" = ${pid})`
);
return and(...checks)!;
}
// contains_any (default) — asset contains at least one of these people
const idList = ids.map((id: string) => `'${id}'`).join(",");
return sql`EXISTS (SELECT 1 FROM "asset_face" af WHERE af."assetId" = ${assets.id} AND af."personId" IN (${sql.raw(idList)}))`;
}
case "person_unnamed":
if (c.match === "no_unnamed") {
return sql`NOT EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`;
}
return sql`EXISTS (SELECT 1 FROM "asset_face" af JOIN "person" p ON af."personId" = p.id WHERE af."assetId" = ${assets.id} AND (p.name = '' OR p.name IS NULL))`;
case "not_in_album":
return sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id})`;
case "not_in_specific_album":
return sql`NOT EXISTS (SELECT 1 FROM "album_asset" aa WHERE aa."assetId" = ${assets.id} AND aa."albumId" = ${c.albumId})`;
case "geo_radius":
if (c.lat !== undefined && c.lng !== undefined && c.radiusKm) {
// Haversine approximation: 1 degree ≈ 111km
const latDelta = c.radiusKm / 111;
const lngDelta = c.radiusKm / (111 * Math.cos((c.lat * Math.PI) / 180));
return and(
gte(exif.latitude, c.lat - latDelta),
lte(exif.latitude, c.lat + latDelta),
gte(exif.longitude, c.lng - lngDelta),
lte(exif.longitude, c.lng + lngDelta),
)!;
}
return undefined;
default:
return undefined;
}
}
+357
View File
@@ -0,0 +1,357 @@
import { appDb } from "@/db";
import { db } from "@/config/db";
import { workflows, workflowNodes, workflowEdges, workflowRuns, workflowProcessedAssets } from "@/db/schema/workflows.schema";
import { assets } from "@/schema/assets.schema";
import { exif } from "@/schema";
import { eq, and, desc, gte, isNull, inArray, sql, ne } from "drizzle-orm";
import { buildConditions } from "./conditionBuilder";
import { executeAction } from "./actionExecutor";
import { IUser } from "@/types/user";
import { randomUUID } from "crypto";
async function resolveAssetTrigger(
subType: string,
workflowId: string,
userId: string,
lookbackMinutes: number = 0,
): Promise<string[]> {
// Get last successful non-debug run time
const [lastRun] = await appDb
.select({ completedAt: workflowRuns.completedAt })
.from(workflowRuns)
.where(and(
eq(workflowRuns.workflowId, workflowId),
eq(workflowRuns.status, "completed"),
ne(workflowRuns.trigger, "debug"),
))
.orderBy(desc(workflowRuns.completedAt))
.limit(1);
// Fall back to workflow creation time if no previous run
let sinceDate = lastRun?.completedAt;
if (!sinceDate) {
const [wf] = await appDb
.select({ createdAt: workflows.createdAt })
.from(workflows)
.where(eq(workflows.id, workflowId))
.limit(1);
sinceDate = wf?.createdAt || new Date();
}
// Apply lookback buffer
if (lookbackMinutes > 0) {
sinceDate = new Date(sinceDate.getTime() - lookbackMinutes * 60 * 1000);
}
const baseConditions = [
eq(assets.ownerId, userId),
eq(assets.visibility, "timeline"),
eq(assets.status, "active"),
isNull(assets.deletedAt),
];
// Get already-processed assets for this workflow
let processedMap: Map<string, Date> | null = null;
if (subType === "new_asset" || subType === "asset_updated") {
const processed = await appDb
.select({ assetId: workflowProcessedAssets.assetId, processedAt: workflowProcessedAssets.processedAt })
.from(workflowProcessedAssets)
.where(eq(workflowProcessedAssets.workflowId, workflowId));
processedMap = new Map(processed.map((r) => [r.assetId, r.processedAt || new Date(0)]));
}
let candidateIds: string[];
if (subType === "new_asset") {
const rows = await db
.selectDistinctOn([assets.id], { id: assets.id })
.from(assets)
.where(and(...baseConditions, gte(assets.createdAt, sinceDate)))
.limit(10000);
// For new_asset: skip any asset we've ever processed
candidateIds = rows.map((r) => r.id).filter((id) => !processedMap?.has(id));
} else if (subType === "asset_updated") {
const rows = await db
.selectDistinctOn([assets.id], { id: assets.id, updatedAt: assets.updatedAt })
.from(assets)
.where(and(...baseConditions, gte(assets.updatedAt, sinceDate)))
.limit(10000);
// For asset_updated: only skip if we processed it AFTER its current updatedAt
candidateIds = rows
.filter((r) => {
const lastProcessed = processedMap?.get(r.id);
if (!lastProcessed) return true; // never processed
return r.updatedAt > lastProcessed; // updated since last processing
})
.map((r) => r.id);
} else {
// all_assets — no dedup
const rows = await db
.selectDistinctOn([assets.id], { id: assets.id })
.from(assets)
.where(and(...baseConditions))
.limit(10000);
return rows.map((r) => r.id);
}
return candidateIds;
}
interface DebugStep {
nodeId: string;
nodeType: string;
subType: string;
label: string;
inputAssets: number;
outputAssets: Record<string, number>;
assetIds?: string[];
detail?: string;
}
interface RunResult {
matchedAssets: number;
assetIds: string[];
actions: any[];
debug?: DebugStep[];
}
export async function executeWorkflow(
workflowId: string,
trigger: "manual" | "schedule" | "webhook" | "debug",
user: IUser
): Promise<string> {
const isDebug = trigger === "debug";
// Create run record
const runId = randomUUID();
await appDb.insert(workflowRuns).values({
id: runId,
workflowId,
trigger,
status: "running",
});
try {
// Load graph
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, workflowId));
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, workflowId));
// Build adjacency map: nodeId -> { handle -> targetNodeId[] }
const adjacency = new Map<string, Map<string | null, string[]>>();
for (const edge of edges) {
if (!adjacency.has(edge.sourceNodeId)) adjacency.set(edge.sourceNodeId, new Map());
const handles = adjacency.get(edge.sourceNodeId)!;
const handle = edge.sourceHandle || null;
if (!handles.has(handle)) handles.set(handle, []);
handles.get(handle)!.push(edge.targetNodeId);
}
const nodeMap = new Map(nodes.map((n) => [n.id, n]));
// Find asset trigger nodes
const triggerNodes = nodes.filter((n) => n.type === "trigger");
if (triggerNodes.length === 0) {
throw new Error("No asset trigger nodes found in the workflow");
}
const result: RunResult = { matchedAssets: 0, assetIds: [], actions: [] };
const debugSteps: DebugStep[] = [];
const allProcessedAssetIds = new Set<string>();
// BFS: process nodes with their incoming asset sets
const queue: { nodeId: string; assetIds: string[] | null }[] = [];
// Resolve each asset trigger to get the initial asset set
for (const triggerNode of triggerNodes) {
const triggerConfig = JSON.parse(triggerNode.data || "{}");
const lookback = triggerConfig.lookbackMinutes || 0;
const assetIds = await resolveAssetTrigger(triggerNode.subType, workflowId, user.id, lookback);
result.matchedAssets += assetIds.length;
debugSteps.push({
nodeId: triggerNode.id,
nodeType: "trigger",
subType: triggerNode.subType,
label: `Asset Trigger: ${triggerNode.subType}`,
inputAssets: 0,
outputAssets: { out: assetIds.length },
assetIds: assetIds.slice(0, 100),
detail: `Lookback: ${lookback}m, Found ${assetIds.length} assets`,
});
const targets = adjacency.get(triggerNode.id)?.get(null) || [];
for (const targetId of targets) {
queue.push({ nodeId: targetId, assetIds });
}
}
// Process queue
while (queue.length > 0) {
const { nodeId, assetIds } = queue.shift()!;
const node = nodeMap.get(nodeId);
if (!node) continue;
const config = JSON.parse(node.data || "{}");
if (node.type === "logic") {
if (node.subType === "if") {
// Query assets matching conditions, scoped to incoming set
const conditions = config.conditions || [];
const whereClauses = buildConditions(conditions, user.id);
// Scope to incoming assets if available
if (assetIds !== null && assetIds.length > 0) {
whereClauses.push(inArray(assets.id, assetIds));
}
const matchedRows = await db
.selectDistinctOn([assets.id], { id: assets.id })
.from(assets)
.leftJoin(exif, eq(assets.id, exif.assetId))
.where(and(...whereClauses))
.limit(10000);
const matchedIds = matchedRows.map((r) => r.id);
const matchedSet = new Set(matchedIds);
let trueIds = matchedIds;
let falseIds: string[] = [];
if (assetIds !== null) {
trueIds = assetIds.filter((id) => matchedSet.has(id));
falseIds = assetIds.filter((id) => !matchedSet.has(id));
}
debugSteps.push({
nodeId: node.id,
nodeType: "logic",
subType: "if",
label: `IF (${conditions.length} conditions)`,
inputAssets: assetIds?.length || 0,
outputAssets: { true: trueIds.length, false: falseIds.length },
assetIds: trueIds.slice(0, 100),
detail: `Matched: ${trueIds.length} true, ${falseIds.length} false`,
});
// Route to true/false branches
const trueTargets = adjacency.get(nodeId)?.get("true") || [];
const falseTargets = adjacency.get(nodeId)?.get("false") || [];
for (const t of trueTargets) queue.push({ nodeId: t, assetIds: trueIds });
for (const t of falseTargets) queue.push({ nodeId: t, assetIds: falseIds });
} else if (node.subType === "switch") {
const cases = config.cases || [];
let remaining = assetIds;
for (const c of cases) {
const whereClauses = buildConditions(c.conditions || [], user.id);
// Scope to remaining assets if available
if (remaining !== null && remaining.length > 0) {
whereClauses.push(inArray(assets.id, remaining));
}
const matchedRows = await db
.selectDistinctOn([assets.id], { id: assets.id })
.from(assets)
.leftJoin(exif, eq(assets.id, exif.assetId))
.where(and(...whereClauses))
.limit(10000);
const matchedIds = matchedRows.map((r) => r.id);
const matchedSet = new Set(matchedIds);
let caseIds: string[];
if (remaining !== null) {
caseIds = remaining.filter((id) => matchedSet.has(id));
remaining = remaining.filter((id) => !matchedSet.has(id));
} else {
caseIds = matchedIds;
remaining = [];
}
result.matchedAssets = Math.max(result.matchedAssets, caseIds.length);
const caseTargets = adjacency.get(nodeId)?.get(c.handle) || [];
for (const t of caseTargets) queue.push({ nodeId: t, assetIds: caseIds });
}
const caseOutput: Record<string, number> = {};
cases.forEach((c: any, i: number) => { caseOutput[c.label || `case_${i}`] = 0; });
// Already routed above, just log
debugSteps.push({
nodeId: node.id,
nodeType: "logic",
subType: "switch",
label: `SWITCH (${cases.length} cases)`,
inputAssets: assetIds?.length || 0,
outputAssets: { ...caseOutput, default: (remaining || []).length },
});
// Default branch gets remaining
const defaultTargets = adjacency.get(nodeId)?.get("default") || [];
for (const t of defaultTargets) queue.push({ nodeId: t, assetIds: remaining || [] });
}
} else if (node.type === "action") {
// Execute action on the asset set
const actionAssetIds = assetIds || [];
actionAssetIds.forEach((id) => allProcessedAssetIds.add(id));
debugSteps.push({
nodeId: node.id,
nodeType: "action",
subType: node.subType,
label: `Action: ${node.subType}`,
inputAssets: actionAssetIds.length,
outputAssets: {},
assetIds: actionAssetIds.slice(0, 100),
detail: isDebug ? `DRY RUN — would process ${actionAssetIds.length} assets` : `Processing ${actionAssetIds.length} assets`,
});
if (!isDebug && actionAssetIds.length > 0) {
const actionResult = await executeAction(node.subType, config, actionAssetIds, user);
result.actions.push({ ...actionResult, assetIds: actionAssetIds });
// Record processed assets to prevent reprocessing
if (actionAssetIds.length > 0) {
const batchSize = 100;
for (let i = 0; i < actionAssetIds.length; i += batchSize) {
const batch = actionAssetIds.slice(i, i + batchSize);
await appDb.insert(workflowProcessedAssets).values(
batch.map((assetId) => ({
workflowId,
assetId,
runId,
}))
);
}
}
}
}
}
// Finalize result
result.assetIds = Array.from(allProcessedAssetIds);
result.matchedAssets = result.assetIds.length;
result.debug = debugSteps;
// Update run record
await appDb.update(workflowRuns).set({
status: "completed",
result: JSON.stringify(result),
completedAt: new Date(),
}).where(eq(workflowRuns.id, runId));
return runId;
} catch (error: any) {
await appDb.update(workflowRuns).set({
status: "failed",
error: error.message || "Unknown error",
completedAt: new Date(),
}).where(eq(workflowRuns.id, runId));
throw error;
}
}
+58
View File
@@ -0,0 +1,58 @@
import cron, { ScheduledTask } from "node-cron";
import { appDb } from "@/db";
import { db } from "@/config/db";
import { workflows } from "@/db/schema/workflows.schema";
import { users } from "@/schema/users.schema";
import { eq, and, isNotNull } from "drizzle-orm";
import { executeWorkflow } from "./engine";
const scheduledTasks = new Map<string, ScheduledTask>();
export async function registerWorkflow(workflowId: string, cronSchedule: string, ownerId: string) {
// Unregister if already exists
unregisterWorkflow(workflowId);
if (!cron.validate(cronSchedule)) {
console.error(`Invalid cron expression for workflow ${workflowId}: ${cronSchedule}`);
return;
}
const task = cron.schedule(cronSchedule, async () => {
try {
const [user] = await db.select().from(users).where(eq(users.id, ownerId));
if (!user) {
console.error(`Owner ${ownerId} not found for workflow ${workflowId}`);
return;
}
await executeWorkflow(workflowId, "schedule", user as any);
console.log(`Scheduled workflow ${workflowId} executed successfully`);
} catch (error: any) {
console.error(`Scheduled workflow ${workflowId} failed:`, error.message);
}
});
scheduledTasks.set(workflowId, task);
}
export function unregisterWorkflow(workflowId: string) {
const existing = scheduledTasks.get(workflowId);
if (existing) {
existing.stop();
scheduledTasks.delete(workflowId);
}
}
export async function loadAllScheduledWorkflows() {
const enabledWorkflows = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.enabled, true), isNotNull(workflows.cronSchedule)));
for (const w of enabledWorkflows) {
if (w.cronSchedule) {
await registerWorkflow(w.id, w.cronSchedule, w.ownerId);
}
}
console.log(`Loaded ${enabledWorkflows.length} scheduled workflows`);
}
+33
View File
@@ -0,0 +1,33 @@
import { appDb } from "@/db";
import { workflows } from "@/db/schema/workflows.schema";
import { eq } from "drizzle-orm";
import { executeWorkflow } from "@/lib/workflow/engine";
import { NextApiRequest, NextApiResponse } from "next";
import { db } from "@/config/db";
import { users } from "@/schema/users.schema";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
const { token } = req.query as { token: string };
const [workflow] = await appDb
.select()
.from(workflows)
.where(eq(workflows.webhookToken, token));
if (!workflow) return res.status(404).json({ message: "Webhook not found" });
if (!workflow.enabled) return res.status(422).json({ message: "Workflow is disabled" });
// Get user from Immich DB
const [user] = await db.select().from(users).where(eq(users.id, workflow.ownerId));
if (!user) return res.status(404).json({ message: "Owner not found" });
try {
const runId = await executeWorkflow(workflow.id, "webhook", user as any);
return res.status(200).json({ runId });
} catch (error: any) {
return res.status(500).json({ message: error.message || "Workflow execution failed" });
}
}
+46
View File
@@ -0,0 +1,46 @@
import { appDb } from "@/db";
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, and } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id } = req.query as { id: string };
const [workflow] = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
const exportData = {
version: 1,
name: workflow.name,
description: workflow.description,
viewport: workflow.viewport,
nodes: nodes.map((n) => ({
id: n.id,
type: n.type,
subType: n.subType,
data: n.data,
positionX: n.positionX,
positionY: n.positionY,
})),
edges: edges.map((e) => ({
id: e.id,
sourceNodeId: e.sourceNodeId,
targetNodeId: e.targetNodeId,
sourceHandle: e.sourceHandle,
})),
};
return res.status(200).json(exportData);
}
+59
View File
@@ -0,0 +1,59 @@
import { appDb } from "@/db";
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, and } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id } = req.query as { id: string };
if (req.method !== "PUT") return res.status(405).json({ message: "Method not allowed" });
const [workflow] = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
const { nodes, edges, viewport } = req.body;
await appDb.delete(workflowEdges).where(eq(workflowEdges.workflowId, id));
await appDb.delete(workflowNodes).where(eq(workflowNodes.workflowId, id));
if (nodes && nodes.length > 0) {
await appDb.insert(workflowNodes).values(
nodes.map((n: any) => ({
id: n.id,
workflowId: id,
type: n.type,
subType: n.subType,
data: typeof n.data === "string" ? n.data : JSON.stringify(n.data),
positionX: n.positionX ?? n.position?.x ?? 0,
positionY: n.positionY ?? n.position?.y ?? 0,
}))
);
}
if (edges && edges.length > 0) {
await appDb.insert(workflowEdges).values(
edges.map((e: any) => ({
id: e.id,
workflowId: id,
sourceNodeId: e.sourceNodeId ?? e.source,
targetNodeId: e.targetNodeId ?? e.target,
sourceHandle: e.sourceHandle ?? null,
}))
);
}
if (viewport) {
await appDb.update(workflows).set({
viewport: typeof viewport === "string" ? viewport : JSON.stringify(viewport),
}).where(eq(workflows.id, id));
}
return res.status(200).json({ success: true });
}
+52
View File
@@ -0,0 +1,52 @@
import { appDb } from "@/db";
import { workflows, workflowNodes, workflowEdges, workflowRuns } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, and, desc } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id } = req.query as { id: string };
if (req.method === "GET") {
const [workflow] = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
const [lastRun] = await appDb
.select()
.from(workflowRuns)
.where(eq(workflowRuns.workflowId, id))
.orderBy(desc(workflowRuns.startedAt))
.limit(1);
return res.status(200).json({ ...workflow, nodes, edges, lastRun: lastRun || null });
}
if (req.method === "PUT") {
const { name, description, enabled, cronSchedule, viewport } = req.body;
const updates: Record<string, any> = {};
if (name !== undefined) updates.name = name;
if (description !== undefined) updates.description = description;
if (enabled !== undefined) updates.enabled = enabled;
if (cronSchedule !== undefined) updates.cronSchedule = cronSchedule;
if (viewport !== undefined) updates.viewport = viewport;
await appDb.update(workflows).set(updates).where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
const [updated] = await appDb.select().from(workflows).where(eq(workflows.id, id));
return res.status(200).json(updated);
}
if (req.method === "DELETE") {
await appDb.delete(workflows).where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
return res.status(204).end();
}
return res.status(405).json({ message: "Method not allowed" });
}
+26
View File
@@ -0,0 +1,26 @@
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { executeWorkflow } from "@/lib/workflow/engine";
import { appDb } from "@/db";
import { workflowRuns } from "@/db/schema/workflows.schema";
import { eq } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id } = req.query as { id: string };
const { mode } = req.body || {};
const trigger = mode === "debug" ? "debug" : "manual";
try {
const runId = await executeWorkflow(id, trigger as any, currentUser);
const [run] = await appDb.select().from(workflowRuns).where(eq(workflowRuns.id, runId));
return res.status(200).json(run);
} catch (error: any) {
return res.status(500).json({ message: error.message || "Workflow execution failed" });
}
}
+30
View File
@@ -0,0 +1,30 @@
import { appDb } from "@/db";
import { workflowRuns, workflows } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, and, desc } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id } = req.query as { id: string };
// Verify ownership
const [workflow] = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
const runs = await appDb
.select()
.from(workflowRuns)
.where(eq(workflowRuns.workflowId, id))
.orderBy(desc(workflowRuns.startedAt))
.limit(20);
return res.status(200).json(runs);
}
@@ -0,0 +1,35 @@
import { appDb } from "@/db";
import { workflows, workflowNodes, workflowEdges, workflowRuns } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, and } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "GET") return res.status(405).json({ message: "Method not allowed" });
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { id, runId } = req.query as { id: string; runId: string };
// Verify ownership
const [workflow] = await appDb
.select()
.from(workflows)
.where(and(eq(workflows.id, id), eq(workflows.ownerId, currentUser.id)));
if (!workflow) return res.status(404).json({ message: "Workflow not found" });
const [run] = await appDb
.select()
.from(workflowRuns)
.where(and(eq(workflowRuns.id, runId), eq(workflowRuns.workflowId, id)));
if (!run) return res.status(404).json({ message: "Run not found" });
const nodes = await appDb.select().from(workflowNodes).where(eq(workflowNodes.workflowId, id));
const edges = await appDb.select().from(workflowEdges).where(eq(workflowEdges.workflowId, id));
return res.status(200).json({
run,
workflow: { ...workflow, nodes, edges },
});
}
+67
View File
@@ -0,0 +1,67 @@
import { appDb } from "@/db";
import { workflows, workflowNodes, workflowEdges } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
import { randomUUID } from "crypto";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
if (req.method !== "POST") return res.status(405).json({ message: "Method not allowed" });
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
const { name, description, viewport, nodes, edges } = req.body;
if (!nodes || !Array.isArray(nodes)) {
return res.status(400).json({ message: "Invalid workflow format: nodes array required" });
}
const workflowId = randomUUID();
const webhookToken = randomUUID();
// Create ID mapping for imported nodes
const idMap = new Map<string, string>();
for (const node of nodes) {
idMap.set(node.id, randomUUID());
}
await appDb.insert(workflows).values({
id: workflowId,
ownerId: currentUser.id,
name: name || "Imported Workflow",
description: description || null,
viewport: viewport || '{"x":0,"y":0,"zoom":1}',
webhookToken,
enabled: false,
});
if (nodes.length > 0) {
await appDb.insert(workflowNodes).values(
nodes.map((n: any) => ({
id: idMap.get(n.id) || randomUUID(),
workflowId,
type: n.type,
subType: n.subType,
data: typeof n.data === "string" ? n.data : JSON.stringify(n.data || {}),
positionX: n.positionX || 0,
positionY: n.positionY || 0,
}))
);
}
if (edges && edges.length > 0) {
await appDb.insert(workflowEdges).values(
edges.map((e: any) => ({
id: randomUUID(),
workflowId,
sourceNodeId: idMap.get(e.sourceNodeId) || e.sourceNodeId,
targetNodeId: idMap.get(e.targetNodeId) || e.targetNodeId,
sourceHandle: e.sourceHandle || null,
}))
);
}
const [created] = await appDb.select().from(workflows).where(eq(workflows.id, workflowId));
return res.status(201).json(created);
}
+37
View File
@@ -0,0 +1,37 @@
import { appDb } from "@/db";
import { workflows } from "@/db/schema/workflows.schema";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { eq, desc } from "drizzle-orm";
import { NextApiRequest, NextApiResponse } from "next";
import { randomUUID } from "crypto";
export default async function handler(req: NextApiRequest, res: NextApiResponse) {
const currentUser = await getCurrentUser(req);
if (!currentUser) return res.status(401).json({ message: "Unauthorized" });
if (req.method === "GET") {
const rows = await appDb
.select()
.from(workflows)
.where(eq(workflows.ownerId, currentUser.id))
.orderBy(desc(workflows.updatedAt));
return res.status(200).json(rows);
}
if (req.method === "POST") {
const { name, description } = req.body;
const id = randomUUID();
const webhookToken = randomUUID();
await appDb.insert(workflows).values({
id,
ownerId: currentUser.id,
name: name || "Untitled Workflow",
description: description || null,
webhookToken,
});
const [row] = await appDb.select().from(workflows).where(eq(workflows.id, id));
return res.status(201).json(row);
}
return res.status(405).json({ message: "Method not allowed" });
}
+547
View File
@@ -0,0 +1,547 @@
import "@xyflow/react/dist/style.css";
import { useRouter } from "next/router";
import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
ReactFlow,
Background,
Controls,
addEdge,
useNodesState,
useEdgesState,
Connection,
Node,
Edge,
ReactFlowProvider,
useReactFlow,
} from "@xyflow/react";
import { nodeTypes } from "@/components/workflows/nodes";
import NodePalette from "@/components/workflows/NodePalette";
import { IfConfig, SwitchConfig, ActionConfig } from "@/components/workflows/config";
import { getWorkflow, saveWorkflowGraph, updateWorkflow, runWorkflow, getWorkflowRuns } from "@/handlers/api/workflow.handler";
import { IWorkflowWithDetails } from "@/types/workflow";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { toast } from "@/components/ui/use-toast";
import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover";
import { Label } from "@/components/ui/label";
import { Badge } from "@/components/ui/badge";
import { ASSET_THUMBNAIL_PATH } from "@/config/routes";
import { IWorkflowRun } from "@/types/workflow";
import { ArrowLeft, Play, Save, Clock, Webhook, History, ChevronUp, ChevronDown, Bug } from "lucide-react";
import { format } from "date-fns";
import Link from "next/link";
import Loader from "@/components/ui/loader";
function generateId() {
return Math.random().toString(36).substring(2, 15);
}
// Map DB node to React Flow node
function dbNodeToFlowNode(n: any): Node {
let flowType = "trigger";
if (n.type === "logic") flowType = n.subType === "switch" ? "logic_switch" : "logic_if";
else if (n.type === "action") flowType = "action";
const config = typeof n.data === "string" ? JSON.parse(n.data || "{}") : (n.data || {});
return {
id: n.id,
type: flowType,
position: { x: n.positionX, y: n.positionY },
data: { subType: n.subType, config, label: n.subType },
};
}
// Map DB edge to React Flow edge
function dbEdgeToFlowEdge(e: any): Edge {
return {
id: e.id,
source: e.sourceNodeId,
target: e.targetNodeId,
sourceHandle: e.sourceHandle || undefined,
animated: true,
};
}
// Map React Flow node back to DB format
function flowNodeToDb(n: Node) {
let dbType = "trigger";
let dbSubType = (n.data?.subType as string) || "manual";
if (n.type === "logic_if") { dbType = "logic"; dbSubType = "if"; }
else if (n.type === "logic_switch") { dbType = "logic"; dbSubType = "switch"; }
else if (n.type === "action") { dbType = "action"; }
return {
id: n.id,
type: dbType,
subType: dbSubType,
data: JSON.stringify(n.data?.config || {}),
positionX: n.position.x,
positionY: n.position.y,
};
}
function flowEdgeToDb(e: Edge) {
return {
id: e.id,
sourceNodeId: e.source,
targetNodeId: e.target,
sourceHandle: e.sourceHandle || null,
};
}
function WorkflowEditorInner() {
const router = useRouter();
const { id } = router.query as { id: string };
const reactFlowWrapper = useRef<HTMLDivElement>(null);
const { screenToFlowPosition } = useReactFlow();
const [workflow, setWorkflow] = useState<IWorkflowWithDetails | null>(null);
const [loading, setLoading] = useState(true);
const [saving, setSaving] = useState(false);
const [running, setRunning] = useState(false);
const [workflowName, setWorkflowName] = useState("");
const [enabled, setEnabled] = useState(false);
const [cronSchedule, setCronSchedule] = useState("");
const [webhookToken, setWebhookToken] = useState<string | null>(null);
const [selectedNode, setSelectedNode] = useState<Node | null>(null);
const [runs, setRuns] = useState<IWorkflowRun[]>([]);
const [showRuns, setShowRuns] = useState(false);
const [expandedRunId, setExpandedRunId] = useState<string | null>(null);
const [nodes, setNodes, onNodesChange] = useNodesState([] as Node[]);
const [edges, setEdges, onEdgesChange] = useEdgesState([] as Edge[]);
useEffect(() => {
if (!id) return;
setLoading(true);
getWorkflow(id)
.then((data) => {
setWorkflow(data);
setWorkflowName(data.name);
setEnabled(data.enabled);
setCronSchedule(data.cronSchedule || "");
setWebhookToken(data.webhookToken || null);
setNodes(data.nodes.map(dbNodeToFlowNode));
setEdges(data.edges.map(dbEdgeToFlowEdge));
})
.catch(() => {
toast({ title: "Error", description: "Failed to load workflow", variant: "destructive" });
})
.finally(() => setLoading(false));
getWorkflowRuns(id).then(setRuns).catch(() => {});
}, [id]);
const onConnect = useCallback((connection: Connection) => {
setEdges((eds) => addEdge({ ...connection, animated: true }, eds));
}, [setEdges]);
const onDragOver = useCallback((event: React.DragEvent) => {
event.preventDefault();
event.dataTransfer.dropEffect = "move";
}, []);
const onDrop = useCallback((event: React.DragEvent) => {
event.preventDefault();
const data = event.dataTransfer.getData("application/reactflow");
if (!data) return;
const { type, subType } = JSON.parse(data);
const position = screenToFlowPosition({ x: event.clientX, y: event.clientY });
let flowType = type;
if (type === "logic_if" || type === "logic_switch") flowType = type;
const newNode: Node = {
id: generateId(),
type: flowType,
position,
data: { subType, config: {}, label: subType },
};
setNodes((nds) => [...nds, newNode]);
}, [screenToFlowPosition, setNodes]);
const onNodeClick = useCallback((_: any, node: Node) => {
setSelectedNode(node);
}, []);
const onPaneClick = useCallback(() => {
setSelectedNode(null);
}, []);
const updateNodeConfig = useCallback((config: any) => {
if (!selectedNode) return;
setNodes((nds) =>
nds.map((n) =>
n.id === selectedNode.id
? { ...n, data: { ...n.data, config } }
: n
)
);
setSelectedNode((prev) => prev ? { ...prev, data: { ...prev.data, config } } : null);
}, [selectedNode, setNodes]);
const handleSave = async () => {
if (!id) return;
setSaving(true);
try {
const viewport = JSON.stringify({ x: 0, y: 0, zoom: 1 });
await saveWorkflowGraph(id, {
nodes: nodes.map(flowNodeToDb),
edges: edges.map(flowEdgeToDb),
viewport,
});
await updateWorkflow(id, {
name: workflowName,
enabled,
cronSchedule: cronSchedule || null,
} as any);
toast({ title: "Saved", description: "Workflow saved" });
} catch {
toast({ title: "Error", description: "Failed to save workflow", variant: "destructive" });
}
setSaving(false);
};
const handleRun = async (mode: "manual" | "debug" = "manual") => {
if (!id) return;
setRunning(true);
try {
await runWorkflow(id, mode);
toast({
title: mode === "debug" ? "Debug Complete" : "Run Complete",
description: mode === "debug" ? "Dry run finished — no actions were executed" : "Workflow execution finished",
});
getWorkflowRuns(id).then(setRuns).catch(() => {});
setShowRuns(true);
} catch {
toast({ title: "Error", description: "Failed to run workflow", variant: "destructive" });
}
setRunning(false);
};
const renderConfigPanel = () => {
if (!selectedNode) return (
<div className="p-4 text-xs text-muted-foreground">
Select a node to configure it.
</div>
);
const { subType, config } = selectedNode.data as { subType: string; config: any };
const nodeType = selectedNode.type;
const typeLabel = nodeType === "trigger" ? "Asset Trigger" : nodeType === "logic_if" ? "If" : nodeType === "logic_switch" ? "Switch" : "Action";
return (
<div className="p-4 space-y-4 overflow-y-auto">
<h3 className="text-sm font-semibold">{typeLabel}: {subType}</h3>
{nodeType === "trigger" && (
<div className="space-y-3">
<p className="text-xs text-muted-foreground">
{subType === "new_asset" && "Selects assets created since the last successful run. On first run, uses workflow creation time."}
{subType === "asset_updated" && "Selects assets updated since the last successful run. On first run, uses workflow creation time."}
{subType === "all_assets" && "Selects all assets in your library. Use with caution on large libraries."}
</p>
{subType !== "all_assets" && (
<div className="space-y-1">
<Label className="text-xs">Lookback Buffer</Label>
<div className="flex items-center gap-2">
<Input
className="h-7 text-xs w-20"
type="number"
min={0}
placeholder="0"
value={config?.lookbackMinutes ?? ""}
onChange={(e) => updateNodeConfig({ ...config, lookbackMinutes: parseInt(e.target.value) || 0 })}
/>
<span className="text-xs text-muted-foreground">minutes before last run</span>
</div>
<p className="text-[10px] text-muted-foreground">
Extends the time window backwards to catch assets that may have been missed. Set to 0 or leave empty for exact last run time.
</p>
</div>
)}
{workflow?.lastRun?.completedAt ? (
<p className="text-[10px] text-muted-foreground">
Last run: {new Date(workflow.lastRun.completedAt).toLocaleString()}
</p>
) : workflow?.createdAt ? (
<p className="text-[10px] text-muted-foreground">
No previous runs. Will use since: {new Date(workflow.createdAt).toLocaleString()}
</p>
) : null}
</div>
)}
{nodeType === "logic_if" && (
<IfConfig config={config || {}} onChange={updateNodeConfig} />
)}
{nodeType === "logic_switch" && (
<SwitchConfig config={config || {}} onChange={updateNodeConfig} />
)}
{nodeType === "action" && (
<ActionConfig subType={subType} config={config || {}} onChange={updateNodeConfig} />
)}
</div>
);
};
if (loading) {
return (
<div className="flex items-center justify-center h-screen">
<Loader />
</div>
);
}
return (
<div className="flex flex-col h-screen">
{/* Top bar */}
<div className="h-12 border-b flex items-center gap-3 px-4 bg-background shrink-0">
<Link href="/workflows" className="text-muted-foreground hover:text-foreground">
<ArrowLeft className="h-4 w-4" />
</Link>
<Input
className="h-8 w-64 text-sm font-medium"
value={workflowName}
onChange={(e) => setWorkflowName(e.target.value)}
/>
<div className="flex items-center gap-2 ml-2">
<span className="text-xs text-muted-foreground">Enabled</span>
<Switch checked={enabled} onCheckedChange={setEnabled} />
</div>
<div className="h-5 w-px bg-border mx-1" />
{/* Schedule config */}
<Popover>
<PopoverTrigger asChild>
<Button variant={cronSchedule ? "secondary" : "ghost"} size="sm" className="h-8">
<Clock className="h-3.5 w-3.5 mr-1" />
{cronSchedule ? "Scheduled" : "Schedule"}
</Button>
</PopoverTrigger>
<PopoverContent className="w-72" align="start">
<div className="space-y-2">
<Label className="text-xs">Cron Expression</Label>
<Input
className="h-8 text-sm font-mono"
placeholder="0 */6 * * *"
value={cronSchedule}
onChange={(e) => setCronSchedule(e.target.value)}
/>
<p className="text-[10px] text-muted-foreground">
e.g. <code>0 */6 * * *</code> (every 6h), <code>0 9 * * 1</code> (Mon 9am). Leave empty to disable.
</p>
</div>
</PopoverContent>
</Popover>
{/* Webhook URL */}
<Popover>
<PopoverTrigger asChild>
<Button variant={webhookToken ? "secondary" : "ghost"} size="sm" className="h-8">
<Webhook className="h-3.5 w-3.5 mr-1" />
Webhook
</Button>
</PopoverTrigger>
<PopoverContent className="w-80" align="start">
<div className="space-y-2">
<Label className="text-xs">Webhook URL</Label>
<Input
className="h-8 text-xs font-mono"
readOnly
value={webhookToken ? `${typeof window !== "undefined" ? window.location.origin : ""}/api/webhooks/${webhookToken}` : "Save workflow first"}
/>
<p className="text-[10px] text-muted-foreground">
Configure this URL in Immich admin webhook settings to trigger this workflow on events.
</p>
</div>
</PopoverContent>
</Popover>
<div className="ml-auto flex items-center gap-2">
<Button variant="outline" size="sm" onClick={() => handleRun("debug")} disabled={running}>
<Bug className="h-3.5 w-3.5 mr-1" />
Debug
</Button>
<Button variant="outline" size="sm" onClick={() => handleRun("manual")} disabled={running}>
<Play className="h-3.5 w-3.5 mr-1" />
{running ? "Running..." : "Run"}
</Button>
<Button size="sm" onClick={handleSave} disabled={saving}>
<Save className="h-3.5 w-3.5 mr-1" />
{saving ? "Saving..." : "Save"}
</Button>
</div>
</div>
{/* Main area */}
<div className="flex flex-1 overflow-hidden">
{/* Left: Node palette */}
<NodePalette />
{/* Center: Canvas */}
<div className="flex-1" ref={reactFlowWrapper}>
<ReactFlow
nodes={nodes}
edges={edges}
onNodesChange={onNodesChange}
onEdgesChange={onEdgesChange}
onConnect={onConnect}
onDrop={onDrop}
onDragOver={onDragOver}
onNodeClick={onNodeClick}
onPaneClick={onPaneClick}
nodeTypes={nodeTypes}
fitView
fitViewOptions={{ maxZoom: 1 }}
defaultViewport={{ x: 0, y: 0, zoom: 0.75 }}
deleteKeyCode={["Backspace", "Delete"]}
>
<Background />
<Controls />
</ReactFlow>
</div>
{/* Right: Config panel */}
<div className="w-72 min-w-[288px] border-l bg-background overflow-y-auto h-full">
{renderConfigPanel()}
</div>
</div>
{/* Runs panel */}
<div className={`border-t bg-background transition-all ${showRuns ? "h-64" : "h-9"}`}>
<button
onClick={() => setShowRuns((v) => !v)}
className="flex items-center gap-2 px-4 h-9 w-full text-left hover:bg-muted transition-colors"
>
<History className="h-3.5 w-3.5 text-muted-foreground" />
<span className="text-xs font-medium">Run History</span>
{runs.length > 0 && <Badge variant="secondary" className="text-[10px] h-4 px-1">{runs.length}</Badge>}
{showRuns ? <ChevronDown className="h-3.5 w-3.5 ml-auto" /> : <ChevronUp className="h-3.5 w-3.5 ml-auto" />}
</button>
{showRuns && (
<div className="overflow-y-auto h-[calc(100%-36px)] px-4">
{runs.length === 0 ? (
<p className="text-xs text-muted-foreground py-4 text-center">No runs yet. Click Run to execute the workflow.</p>
) : (
<div className="space-y-1 pb-2">
{runs.map((run) => {
const result = run.result ? (typeof run.result === "string" ? JSON.parse(run.result) : run.result) : {};
const isExpanded = expandedRunId === run.id;
return (
<div key={run.id} className="border rounded">
<button
onClick={() => setExpandedRunId(isExpanded ? null : run.id)}
className="flex items-center gap-2 px-3 py-1.5 w-full text-left hover:bg-muted/50 transition-colors"
>
<Badge
variant={run.status === "completed" ? "default" : run.status === "failed" ? "destructive" : "secondary"}
className="text-[10px] h-4 px-1"
>
{run.status}
</Badge>
<span className="text-[10px] text-muted-foreground">{run.trigger}</span>
<span className="text-[10px] text-muted-foreground ml-auto">
{run.startedAt ? format(new Date(run.startedAt), "MMM d, HH:mm:ss") : ""}
</span>
<span className="text-[10px] font-medium">{result.matchedAssets || 0} assets</span>
<Link
href={`/workflows/${id}/runs/${run.id}`}
onClick={(e) => e.stopPropagation()}
className="text-[10px] text-blue-500 hover:underline ml-1"
>
View
</Link>
{isExpanded ? <ChevronUp className="h-3 w-3" /> : <ChevronDown className="h-3 w-3" />}
</button>
{isExpanded && (
<div className="px-3 pb-2 space-y-2">
{run.error && (
<p className="text-[10px] text-destructive">{run.error}</p>
)}
{result.actions && result.actions.length > 0 && (
<div>
<p className="text-[10px] font-medium text-muted-foreground mb-1">Actions:</p>
{result.actions.map((a: any, i: number) => (
<div key={i} className="text-[10px] text-muted-foreground">
{a.action}: {a.assetsProcessed} assets
{a.albumName && ` → "${a.albumName}"`}
{a.error && <span className="text-destructive"> ({a.error})</span>}
</div>
))}
</div>
)}
{result.debug && result.debug.length > 0 && (
<div>
<p className="text-[10px] font-medium text-muted-foreground mb-1">Debug Steps:</p>
<div className="space-y-1.5">
{result.debug.map((step: any, i: number) => (
<div key={i} className="text-[10px] border rounded p-1.5 bg-muted/30">
<div className="flex items-center gap-1.5">
<Badge variant="outline" className="text-[9px] h-3.5 px-1">{step.nodeType}</Badge>
<span className="font-medium">{step.label}</span>
</div>
{step.detail && <p className="text-muted-foreground mt-0.5">{step.detail}</p>}
<div className="flex gap-2 mt-0.5">
<span className="text-muted-foreground">In: {step.inputAssets}</span>
{Object.entries(step.outputAssets).map(([k, v]) => (
<span key={k} className="text-muted-foreground">{k}: {v as number}</span>
))}
</div>
{step.assetIds && step.assetIds.length > 0 && (
<div className="flex flex-wrap gap-0.5 mt-1">
{step.assetIds.slice(0, 20).map((aid: string) => (
<img key={aid} src={ASSET_THUMBNAIL_PATH(aid)} alt="" className="h-6 w-6 rounded object-cover" />
))}
{step.assetIds.length > 20 && <span className="text-muted-foreground self-center ml-1">+{step.assetIds.length - 20}</span>}
</div>
)}
</div>
))}
</div>
</div>
)}
{result.assetIds && result.assetIds.length > 0 && (
<div>
<p className="text-[10px] font-medium text-muted-foreground mb-1">Assets ({result.assetIds.length}):</p>
<div className="flex flex-wrap gap-1 max-h-24 overflow-y-auto">
{result.assetIds.slice(0, 50).map((assetId: string) => (
<img
key={assetId}
src={ASSET_THUMBNAIL_PATH(assetId)}
alt=""
className="h-8 w-8 rounded object-cover"
/>
))}
{result.assetIds.length > 50 && (
<span className="text-[10px] text-muted-foreground self-center">+{result.assetIds.length - 50} more</span>
)}
</div>
</div>
)}
</div>
)}
</div>
);
})}
</div>
)}
</div>
)}
</div>
</div>
);
}
export default function WorkflowEditorPage() {
return (
<ReactFlowProvider>
<WorkflowEditorInner />
</ReactFlowProvider>
);
}
+367
View File
@@ -0,0 +1,367 @@
import "@xyflow/react/dist/style.css";
import { useRouter } from "next/router";
import { useEffect, useMemo, useState } from "react";
import {
ReactFlow,
Background,
Controls,
Node,
Edge,
ReactFlowProvider,
} from "@xyflow/react";
import { Badge } from "@/components/ui/badge";
import { Button } from "@/components/ui/button";
import { ASSET_THUMBNAIL_PATH } from "@/config/routes";
import { ArrowLeft, CheckCircle, XCircle, Clock, Bug } from "lucide-react";
import { format } from "date-fns";
import Link from "next/link";
import Loader from "@/components/ui/loader";
import API from "@/lib/api";
import { Handle, Position, NodeProps } from "@xyflow/react";
import {
FilePlus, FileEdit, Database, GitBranch, GitFork,
FolderPlus, FolderInput, FolderMinus, Heart, HeartOff, Archive, Tag,
} from "lucide-react";
// ---- Annotated Node Components (read-only, with run data) ----
function AnnotatedTriggerNode({ data, selected }: NodeProps) {
const subType = data.subType as string;
const step = data.runStep as any;
const icons: Record<string, any> = { new_asset: FilePlus, asset_updated: FileEdit, all_assets: Database };
const labels: Record<string, string> = { new_asset: "New Asset", asset_updated: "Asset Updated", all_assets: "All Assets" };
const Icon = icons[subType] || FilePlus;
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[200px] ${step ? "border-green-500" : "border-muted"}`}>
<div className="flex items-center gap-2">
<div className="p-1.5 rounded bg-green-500/10">
<Icon className="h-4 w-4 text-green-500" />
</div>
<div className="flex-1">
<p className="text-xs font-medium">{labels[subType] || "Trigger"}</p>
{step && <p className="text-[10px] text-muted-foreground">{step.detail}</p>}
</div>
{step && (
<Badge variant="secondary" className="text-[10px] h-4 px-1">
{step.outputAssets?.out || 0}
</Badge>
)}
</div>
{step?.assetIds && step.assetIds.length > 0 && (
<div className="flex flex-wrap gap-0.5 mt-2">
{step.assetIds.slice(0, 8).map((id: string) => (
<img key={id} src={ASSET_THUMBNAIL_PATH(id)} alt="" className="h-5 w-5 rounded object-cover" />
))}
{step.assetIds.length > 8 && <span className="text-[9px] text-muted-foreground self-center">+{step.assetIds.length - 8}</span>}
</div>
)}
<Handle type="source" position={Position.Bottom} className="!bg-green-500 !w-3 !h-3" />
</div>
);
}
function AnnotatedIfNode({ data }: NodeProps) {
const step = data.runStep as any;
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[200px] ${step ? "border-yellow-500" : "border-muted"}`}>
<Handle type="target" position={Position.Top} className="!bg-yellow-500 !w-3 !h-3" />
<div className="flex items-center gap-2 mb-1">
<div className="p-1.5 rounded bg-yellow-500/10">
<GitBranch className="h-4 w-4 text-yellow-500" />
</div>
<p className="text-xs font-medium">IF</p>
{step && <span className="text-[10px] text-muted-foreground ml-auto">in: {step.inputAssets}</span>}
</div>
{step && (
<div className="flex gap-3 text-[10px] mt-1">
<span className="text-green-500">true: {step.outputAssets?.true || 0}</span>
<span className="text-red-500">false: {step.outputAssets?.false || 0}</span>
</div>
)}
{step?.assetIds && step.assetIds.length > 0 && (
<div className="flex flex-wrap gap-0.5 mt-2">
{step.assetIds.slice(0, 6).map((id: string) => (
<img key={id} src={ASSET_THUMBNAIL_PATH(id)} alt="" className="h-5 w-5 rounded object-cover" />
))}
{step.assetIds.length > 6 && <span className="text-[9px] text-muted-foreground self-center">+{step.assetIds.length - 6}</span>}
</div>
)}
<div className="flex justify-between mt-2 px-2">
<Handle type="source" position={Position.Bottom} id="true" className="!bg-green-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0" />
<Handle type="source" position={Position.Bottom} id="false" className="!bg-red-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0" />
</div>
</div>
);
}
function AnnotatedSwitchNode({ data }: NodeProps) {
const step = data.runStep as any;
const config = data.config ? (typeof data.config === "string" ? JSON.parse(data.config) : data.config) : {};
const cases = config.cases || [];
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[220px] ${step ? "border-orange-500" : "border-muted"}`}>
<Handle type="target" position={Position.Top} className="!bg-orange-500 !w-3 !h-3" />
<div className="flex items-center gap-2 mb-1">
<div className="p-1.5 rounded bg-orange-500/10">
<GitFork className="h-4 w-4 text-orange-500" />
</div>
<p className="text-xs font-medium">SWITCH</p>
{step && <span className="text-[10px] text-muted-foreground ml-auto">in: {step.inputAssets}</span>}
</div>
{step && (
<div className="flex flex-wrap gap-2 text-[10px] mt-1">
{Object.entries(step.outputAssets || {}).map(([k, v]) => (
<span key={k} className="text-orange-500">{k}: {v as number}</span>
))}
</div>
)}
<div className="flex justify-between mt-2 px-1 gap-2">
{cases.map((c: any, i: number) => (
<Handle key={c.handle || `case_${i}`} type="source" position={Position.Bottom} id={c.handle || `case_${i}`} className="!bg-orange-500 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0" />
))}
<Handle type="source" position={Position.Bottom} id="default" className="!bg-gray-400 !w-2.5 !h-2.5 !relative !transform-none !left-0 !top-0" />
</div>
</div>
);
}
function AnnotatedActionNode({ data }: NodeProps) {
const subType = data.subType as string;
const step = data.runStep as any;
const icons: Record<string, any> = {
create_album: FolderPlus, add_to_album: FolderInput, remove_from_album: FolderMinus,
favorite: Heart, unfavorite: HeartOff, archive: Archive, tag: Tag,
};
const labels: Record<string, string> = {
create_album: "Create Album", add_to_album: "Add to Album", remove_from_album: "Remove from Album",
favorite: "Favorite", unfavorite: "Unfavorite", archive: "Archive", tag: "Add Tag",
};
const Icon = icons[subType] || FolderPlus;
const isDryRun = step?.detail?.includes("DRY RUN");
return (
<div className={`px-4 py-3 rounded-lg border-2 bg-background min-w-[200px] ${step ? (isDryRun ? "border-blue-500" : "border-purple-500") : "border-muted"}`}>
<Handle type="target" position={Position.Top} className="!bg-purple-500 !w-3 !h-3" />
<div className="flex items-center gap-2">
<div className={`p-1.5 rounded ${isDryRun ? "bg-blue-500/10" : "bg-purple-500/10"}`}>
<Icon className={`h-4 w-4 ${isDryRun ? "text-blue-500" : "text-purple-500"}`} />
</div>
<div className="flex-1">
<p className="text-xs font-medium">{labels[subType] || "Action"}</p>
{step && <p className="text-[10px] text-muted-foreground">{step.detail}</p>}
</div>
{step && (
<Badge variant={isDryRun ? "outline" : "secondary"} className="text-[10px] h-4 px-1">
{step.inputAssets}
</Badge>
)}
</div>
{step?.assetIds && step.assetIds.length > 0 && (
<div className="flex flex-wrap gap-0.5 mt-2">
{step.assetIds.slice(0, 8).map((id: string) => (
<img key={id} src={ASSET_THUMBNAIL_PATH(id)} alt="" className="h-5 w-5 rounded object-cover" />
))}
{step.assetIds.length > 8 && <span className="text-[9px] text-muted-foreground self-center">+{step.assetIds.length - 8}</span>}
</div>
)}
</div>
);
}
const annotatedNodeTypes = {
trigger: AnnotatedTriggerNode,
logic_if: AnnotatedIfNode,
logic_switch: AnnotatedSwitchNode,
action: AnnotatedActionNode,
};
// ---- Page Component ----
function dbNodeToFlowNode(n: any, debugSteps: any[]): Node {
let flowType = "trigger";
if (n.type === "logic") flowType = n.subType === "switch" ? "logic_switch" : "logic_if";
else if (n.type === "action") flowType = "action";
const config = typeof n.data === "string" ? JSON.parse(n.data || "{}") : (n.data || {});
const runStep = debugSteps.find((s: any) => s.nodeId === n.id) || null;
return {
id: n.id,
type: flowType,
position: { x: n.positionX, y: n.positionY },
data: { subType: n.subType, config, label: n.subType, runStep },
draggable: false,
connectable: false,
selectable: false,
};
}
function dbEdgeToFlowEdge(e: any): Edge {
return {
id: e.id,
source: e.sourceNodeId,
target: e.targetNodeId,
sourceHandle: e.sourceHandle || undefined,
animated: true,
};
}
function RunDetailInner() {
const router = useRouter();
const { id, runId } = router.query as { id: string; runId: string };
const [loading, setLoading] = useState(true);
const [data, setData] = useState<any>(null);
const [selectedNodeAssets, setSelectedNodeAssets] = useState<string[] | null>(null);
useEffect(() => {
if (!id || !runId) return;
setLoading(true);
API.get(`/api/workflows/${id}/runs/${runId}`)
.then(setData)
.catch(() => {})
.finally(() => setLoading(false));
}, [id, runId]);
const { nodes, edges, run, result } = useMemo(() => {
if (!data) return { nodes: [], edges: [], run: null, result: null };
const runData = data.run;
const resultParsed = runData.result ? (typeof runData.result === "string" ? JSON.parse(runData.result) : runData.result) : {};
const debugSteps = resultParsed.debug || resultParsed.actions?.map((a: any) => ({
nodeId: "",
nodeType: "action",
subType: a.action,
label: `Action: ${a.action}`,
inputAssets: a.assetsProcessed,
outputAssets: {},
assetIds: a.assetIds,
})) || [];
const flowNodes = data.workflow.nodes.map((n: any) => dbNodeToFlowNode(n, debugSteps));
const flowEdges = data.workflow.edges.map((e: any) => dbEdgeToFlowEdge(e));
return { nodes: flowNodes, edges: flowEdges, run: runData, result: resultParsed };
}, [data]);
if (loading) {
return <div className="flex items-center justify-center h-screen"><Loader /></div>;
}
if (!data || !run) {
return (
<div className="flex flex-col items-center justify-center h-screen gap-4">
<p className="text-muted-foreground">Run not found</p>
<Link href={`/workflows/${id}`}><Button variant="outline" size="sm">Back to Editor</Button></Link>
</div>
);
}
const statusIcon = run.status === "completed"
? <CheckCircle className="h-4 w-4 text-green-500" />
: run.status === "failed"
? <XCircle className="h-4 w-4 text-destructive" />
: <Clock className="h-4 w-4 text-muted-foreground" />;
return (
<div className="flex flex-col h-screen">
{/* Top bar */}
<div className="h-12 border-b flex items-center gap-3 px-4 bg-background shrink-0">
<Link href={`/workflows/${id}`} className="text-muted-foreground hover:text-foreground">
<ArrowLeft className="h-4 w-4" />
</Link>
<span className="text-sm font-medium">Run Detail</span>
<div className="flex items-center gap-2">
{statusIcon}
<Badge variant={run.status === "completed" ? "default" : run.status === "failed" ? "destructive" : "secondary"} className="text-xs">
{run.status}
</Badge>
{run.trigger === "debug" && (
<Badge variant="outline" className="text-xs">
<Bug className="h-3 w-3 mr-1" />
Debug (Dry Run)
</Badge>
)}
</div>
<span className="text-xs text-muted-foreground ml-2">
{run.startedAt ? format(new Date(run.startedAt), "MMM d, yyyy HH:mm:ss") : ""}
</span>
<span className="text-xs font-medium ml-auto">
{result?.matchedAssets || 0} assets processed
</span>
</div>
{/* Main area */}
<div className="flex flex-1 overflow-hidden">
{/* Graph */}
<div className="flex-1">
<ReactFlow
nodes={nodes}
edges={edges}
nodeTypes={annotatedNodeTypes}
fitView
fitViewOptions={{ maxZoom: 1 }}
nodesDraggable={false}
nodesConnectable={false}
elementsSelectable={false}
panOnDrag
zoomOnScroll
onNodeClick={(_, node) => {
const step = node.data?.runStep as any;
if (step?.assetIds && step.assetIds.length > 0) {
setSelectedNodeAssets(step.assetIds);
} else {
setSelectedNodeAssets(null);
}
}}
onPaneClick={() => setSelectedNodeAssets(null)}
>
<Background />
<Controls />
</ReactFlow>
</div>
{/* Side panel — asset list for selected node */}
{selectedNodeAssets && (
<div className="w-72 border-l bg-background overflow-y-auto p-4">
<div className="flex items-center justify-between mb-3">
<h3 className="text-sm font-semibold">Assets ({selectedNodeAssets.length})</h3>
<Button variant="ghost" size="sm" className="h-6 px-2 text-xs" onClick={() => setSelectedNodeAssets(null)}>
Close
</Button>
</div>
<div className="grid grid-cols-3 gap-1">
{selectedNodeAssets.map((assetId) => (
<img
key={assetId}
src={ASSET_THUMBNAIL_PATH(assetId)}
alt=""
className="w-full aspect-square rounded object-cover"
/>
))}
</div>
</div>
)}
</div>
{/* Error bar */}
{run.error && (
<div className="border-t bg-destructive/10 px-4 py-2">
<p className="text-xs text-destructive">{run.error}</p>
</div>
)}
</div>
);
}
export default function RunDetailPage() {
return (
<ReactFlowProvider>
<RunDetailInner />
</ReactFlowProvider>
);
}
+175
View File
@@ -0,0 +1,175 @@
import PageLayout from "@/components/layouts/PageLayout";
import Header from "@/components/shared/Header";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { AlertDialog } from "@/components/ui/alert-dialog";
import Loader from "@/components/ui/loader";
import { listWorkflows, createWorkflow, deleteWorkflow, exportWorkflow, importWorkflow } from "@/handlers/api/workflow.handler";
import { IWorkflow } from "@/types/workflow";
import { Plus, Download, Upload, Trash2, Pencil, Workflow } from "lucide-react";
import { useEffect, useRef, useState } from "react";
import { useRouter } from "next/router";
import { toast } from "@/components/ui/use-toast";
import { format } from "date-fns";
export default function WorkflowsPage() {
const router = useRouter();
const [workflows, setWorkflows] = useState<IWorkflow[]>([]);
const [loading, setLoading] = useState(true);
const fileInputRef = useRef<HTMLInputElement>(null);
const fetchWorkflows = async () => {
setLoading(true);
try {
const data = await listWorkflows();
setWorkflows(data);
} catch {
toast({ title: "Error", description: "Failed to load workflows", variant: "destructive" });
}
setLoading(false);
};
useEffect(() => {
fetchWorkflows();
}, []);
const handleCreate = async () => {
try {
const workflow = await createWorkflow({ name: "Untitled Workflow" });
router.push(`/workflows/${workflow.id}`);
} catch {
toast({ title: "Error", description: "Failed to create workflow", variant: "destructive" });
}
};
const handleDelete = async (id: string) => {
try {
await deleteWorkflow(id);
setWorkflows((prev) => prev.filter((w) => w.id !== id));
toast({ title: "Deleted", description: "Workflow deleted" });
} catch {
toast({ title: "Error", description: "Failed to delete workflow", variant: "destructive" });
}
};
const handleExport = async (id: string, name: string) => {
try {
const data = await exportWorkflow(id);
const blob = new Blob([JSON.stringify(data, null, 2)], { type: "application/json" });
const url = URL.createObjectURL(blob);
const a = document.createElement("a");
a.href = url;
a.download = `${name.replace(/[^a-zA-Z0-9]/g, "_")}.workflow.json`;
a.click();
URL.revokeObjectURL(url);
} catch {
toast({ title: "Error", description: "Failed to export workflow", variant: "destructive" });
}
};
const handleImport = async (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (!file) return;
try {
const text = await file.text();
const data = JSON.parse(text);
const workflow = await importWorkflow(data);
setWorkflows((prev) => [workflow, ...prev]);
toast({ title: "Imported", description: `Workflow "${workflow.name}" imported` });
} catch {
toast({ title: "Error", description: "Failed to import workflow. Check the file format.", variant: "destructive" });
}
if (fileInputRef.current) fileInputRef.current.value = "";
};
return (
<PageLayout>
<Header
leftComponent="Workflows"
rightComponent={
<div className="flex items-center gap-2">
<input
ref={fileInputRef}
type="file"
accept=".json"
className="hidden"
onChange={handleImport}
/>
<Button variant="outline" size="sm" onClick={() => fileInputRef.current?.click()}>
<Upload className="h-4 w-4 mr-1" />
Import
</Button>
<Button size="sm" onClick={handleCreate}>
<Plus className="h-4 w-4 mr-1" />
New Workflow
</Button>
</div>
}
/>
{loading ? (
<div className="flex justify-center py-12"><Loader /></div>
) : workflows.length === 0 ? (
<div className="flex flex-col items-center justify-center py-20 text-center">
<Workflow className="h-12 w-12 text-muted-foreground mb-4" />
<h3 className="text-lg font-medium mb-2">No workflows yet</h3>
<p className="text-sm text-muted-foreground mb-4">
Create your first workflow to start automating your library organization.
</p>
<Button onClick={handleCreate}>
<Plus className="h-4 w-4 mr-1" />
Create Workflow
</Button>
</div>
) : (
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-4 p-4">
{workflows.map((w) => (
<Card key={w.id} className="flex flex-col">
<CardHeader className="pb-2">
<div className="flex items-start justify-between">
<div className="flex-1 min-w-0">
<CardTitle className="text-base truncate">{w.name}</CardTitle>
{w.description && (
<CardDescription className="mt-1 line-clamp-2">{w.description}</CardDescription>
)}
</div>
<Badge variant={w.enabled ? "default" : "secondary"} className="ml-2 shrink-0">
{w.enabled ? "Enabled" : "Disabled"}
</Badge>
</div>
</CardHeader>
<CardContent className="flex-1 flex flex-col justify-end gap-3">
<div className="flex items-center gap-2 text-xs text-muted-foreground">
{w.cronSchedule && <Badge variant="outline" className="text-xs">Scheduled</Badge>}
{w.webhookToken && <Badge variant="outline" className="text-xs">Webhook</Badge>}
<span className="ml-auto">
{w.updatedAt ? format(new Date(w.updatedAt), "MMM d, yyyy") : ""}
</span>
</div>
<div className="flex items-center gap-2">
<Button variant="outline" size="sm" className="flex-1" onClick={() => router.push(`/workflows/${w.id}`)}>
<Pencil className="h-3.5 w-3.5 mr-1" />
Edit
</Button>
<Button variant="ghost" size="sm" onClick={() => handleExport(w.id, w.name)}>
<Download className="h-3.5 w-3.5" />
</Button>
<AlertDialog
title="Delete workflow?"
description={`This will permanently delete "${w.name}" and all its nodes, edges, and run history.`}
onConfirm={() => handleDelete(w.id)}
>
<Button variant="ghost" size="sm">
<Trash2 className="h-3.5 w-3.5 text-destructive" />
</Button>
</AlertDialog>
</div>
</CardContent>
</Card>
))}
</div>
)}
</PageLayout>
);
}
+85
View File
@@ -0,0 +1,85 @@
export interface IWorkflow {
id: string;
ownerId: string;
name: string;
description: string | null;
enabled: boolean;
cronSchedule: string | null;
webhookToken: string | null;
viewport: string;
createdAt: Date;
updatedAt: Date;
}
export interface IWorkflowNode {
id: string;
workflowId: string;
type: "trigger" | "logic" | "action";
subType: string;
data: string;
positionX: number;
positionY: number;
createdAt: Date;
}
export interface IWorkflowEdge {
id: string;
workflowId: string;
sourceNodeId: string;
targetNodeId: string;
sourceHandle: string | null;
createdAt: Date;
}
export interface IWorkflowRun {
id: string;
workflowId: string;
trigger: "manual" | "schedule" | "webhook";
status: "running" | "completed" | "failed";
result: string;
error: string | null;
startedAt: Date;
completedAt: Date | null;
}
export interface IWorkflowWithDetails extends IWorkflow {
nodes: IWorkflowNode[];
edges: IWorkflowEdge[];
lastRun?: IWorkflowRun | null;
}
export type ConditionType =
| "person" | "person_unnamed"
| "city" | "state" | "country" | "geo_radius"
| "date_range" | "date_relative" | "day_of_week"
| "camera_make" | "camera_model" | "lens"
| "asset_type" | "iso_range" | "focal_length"
| "rating" | "is_favorited"
| "not_in_album" | "not_in_specific_album";
export interface ICondition {
type: ConditionType;
[key: string]: any;
}
export interface IManualTriggerData {}
export interface IScheduleTriggerData { cron: string; }
export interface IWebhookTriggerData { token: string; }
export interface IIfNodeData { conditions: ICondition[]; }
export interface ISwitchCase { label: string; conditions: ICondition[]; handle: string; }
export interface ISwitchNodeData { cases: ISwitchCase[]; }
export interface ICreateAlbumActionData { nameTemplate: string; }
export interface IAddToAlbumActionData { albumId: string; }
export interface IRemoveFromAlbumActionData { albumId: string; }
export interface ITagActionData { tagName: string; }
export interface IWorkflowExport {
version: number;
name: string;
description: string | null;
viewport: string;
nodes: Omit<IWorkflowNode, "workflowId" | "createdAt">[];
edges: Omit<IWorkflowEdge, "workflowId" | "createdAt">[];
}