Open-source personal finance manager. Self-hosted, privacy-first.
feat: create rule from transaction (#251)
Geovane Pereirae0e52a575aee
diff --git a/frontend/src/components/rule-dialog.tsx b/frontend/src/components/rule-dialog.tsxnew file mode 100644index 00000000..6c36cbed--- /dev/null+++ b/frontend/src/components/rule-dialog.tsx@@ -0,0 +1,339 @@+import { useState } from 'react'+import { useTranslation } from 'react-i18next'+import { getAccountName } from '@/lib/account-utils'+import { Input } from '@/components/ui/input'+import { Label } from '@/components/ui/label'+import { Button } from '@/components/ui/button'+import {+ Dialog,+ DialogContent,+ DialogHeader,+ DialogTitle,+ DialogFooter,+} from '@/components/ui/dialog'+import { X, Plus } from 'lucide-react'+import { cn } from '@/lib/utils'+import { CategorySelect } from '@/components/category-select'+import type { Category, CategoryGroup, Payee, Rule, RuleCondition, RuleAction } from '@/types'++const CONDITION_FIELDS = [+ { value: 'description', label: 'rules.fieldDescription' },+ { value: 'notes', label: 'rules.fieldNotes' },+ { value: 'amount', label: 'rules.fieldAmount' },+ { value: 'type', label: 'rules.fieldType' },+ { value: 'account_id', label: 'rules.fieldAccount' },+ { value: 'payee_id', label: 'rules.fieldPayee' },+ { value: 'date', label: 'rules.fieldDate' },+] as const++const STRING_OPS = [+ { value: 'contains', label: 'rules.opContains' },+ { value: 'not_contains', label: 'rules.opNotContains' },+ { value: 'equals', label: 'rules.opEquals' },+ { value: 'not_equals', label: 'rules.opNotEquals' },+ { value: 'starts_with', label: 'rules.opStartsWith' },+ { value: 'ends_with', label: 'rules.opEndsWith' },+ { value: 'regex', label: 'rules.opRegex' },+]++const NUMERIC_OPS = [+ { value: 'equals', label: '=' },+ { value: 'gt', label: '>' },+ { value: 'gte', label: '>=' },+ { value: 'lt', label: '<' },+ { value: 'lte', label: '<=' },+]++function getOpsForField(field: string) {+ if (field === 'amount' || field === 'date') return NUMERIC_OPS+ if (field === 'type') return [{ value: 'equals', label: 'rules.opIs' }]+ if (field === 'payee_id' || field === 'account_id') return [+ { value: 'equals', label: 'rules.opIs' },+ { value: 'not_equals', label: 'rules.opIsNot' },+ ]+ return STRING_OPS+}++export interface RuleDialogInitialData {+ name?: string+ conditions?: RuleCondition[]+ actions?: RuleAction[]+}++export function RuleDialog({+ open, onClose, rule, categories, categoryGroups, accounts, payees, onSave, loading, initialData,+}: {+ open: boolean+ onClose: () => void+ rule: Rule | null+ categories: Category[]+ categoryGroups: CategoryGroup[]+ accounts: { id: string; name: string }[]+ payees: Payee[]+ onSave: (data: Partial<Rule>) => void+ loading: boolean+ initialData?: RuleDialogInitialData+}) {+ const { t } = useTranslation()++ const defaultConditions: RuleCondition[] = initialData?.conditions ?? rule?.conditions as RuleCondition[] ?? [{ field: 'description', op: 'contains', value: '' }]+ const defaultActions: RuleAction[] = initialData?.actions ?? rule?.actions as RuleAction[] ?? [{ op: 'set_category', value: '' }]++ const [name, setName] = useState(initialData?.name ?? rule?.name ?? '')+ const [conditionsOp, setConditionsOp] = useState<'and' | 'or'>(rule?.conditions_op ?? 'and')+ const [conditions, setConditions] = useState<RuleCondition[]>(+ defaultConditions.length ? defaultConditions : [{ field: 'description', op: 'contains', value: '' }]+ )+ const [actions, setActions] = useState<RuleAction[]>(+ defaultActions.length ? defaultActions : [{ op: 'set_category', value: '' }]+ )+ const [priority, setPriority] = useState(rule?.priority ?? 0)+ const [isActive, setIsActive] = useState(rule?.is_active ?? true)++ const selectClass = 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'++ function updateCondition(i: number, field: keyof RuleCondition, val: string | number) {+ setConditions(prev => prev.map((c, idx) => idx === i ? { ...c, [field]: val } : c))+ }++ function removeCondition(i: number) {+ setConditions(prev => prev.filter((_, idx) => idx !== i))+ }++ function addCondition() {+ setConditions(prev => [...prev, { field: 'description', op: 'contains', value: '' }])+ }++ function updateAction(i: number, field: keyof RuleAction, val: string) {+ setActions(prev => prev.map((a, idx) => {+ if (idx !== i) return a+ const next = { ...a, [field]: val }+ if (field === 'op') next.value = ''+ return next+ }))+ }++ function removeAction(i: number) {+ setActions(prev => prev.filter((_, idx) => idx !== i))+ }++ function addAction() {+ setActions(prev => [...prev, { op: 'set_category', value: '' }])+ }++ function handleSubmit(e: React.FormEvent) {+ e.preventDefault()+ onSave({ name, conditions_op: conditionsOp, conditions, actions, priority, is_active: isActive })+ }++ return (+ <Dialog open={open} onOpenChange={onClose}>+ <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto overflow-x-hidden">+ <DialogHeader>+ <DialogTitle>{rule ? t('rules.editRule') : t('rules.newRule')}</DialogTitle>+ </DialogHeader>+ <form key={rule?.id ?? 'new'} onSubmit={handleSubmit} className="space-y-5">+ {/* Name + Priority */}+ <div className="grid grid-cols-3 gap-3">+ <div className="col-span-2 space-y-1.5">+ <Label>{t('rules.name')}</Label>+ <Input value={name} onChange={(e) => setName(e.target.value)} required placeholder="Ex: Uber" />+ </div>+ <div className="space-y-1.5">+ <Label>{t('rules.priority')}</Label>+ <Input type="number" value={priority} onChange={(e) => setPriority(Number(e.target.value))} />+ </div>+ </div>++ {/* Conditions */}+ <div className="space-y-2">+ <div className="flex items-center justify-between">+ <Label>{t('rules.conditions')}</Label>+ <div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">+ {(['and', 'or'] as const).map(op => (+ <button+ key={op}+ type="button"+ className={cn(+ 'px-3 py-1 text-xs font-semibold rounded-md transition-all',+ conditionsOp === op ? 'bg-card shadow-sm text-foreground' : 'text-muted-foreground hover:text-foreground'+ )}+ onClick={() => setConditionsOp(op)}+ >+ {op === 'and' ? t('rules.andOp') : t('rules.orOp')}+ </button>+ ))}+ </div>+ </div>+ <div className="space-y-2">+ {conditions.map((cond, i) => (+ <div key={i} className="flex items-center gap-2 min-w-0">+ <select+ className={`${selectClass} w-32 shrink-0`}+ value={cond.field}+ onChange={(e) => updateCondition(i, 'field', e.target.value)}+ >+ {CONDITION_FIELDS.map(f => (+ <option key={f.value} value={f.value}>{t(f.label)}</option>+ ))}+ </select>+ <select+ className={`${selectClass} w-32 shrink-0`}+ value={cond.op}+ onChange={(e) => updateCondition(i, 'op', e.target.value)}+ >+ {getOpsForField(cond.field).map(o => (+ <option key={o.value} value={o.value}>{t(o.label)}</option>+ ))}+ </select>+ {cond.field === 'type' ? (+ <select+ className={`${selectClass} w-0 flex-1 min-w-0`}+ value={String(cond.value)}+ onChange={(e) => updateCondition(i, 'value', e.target.value)}+ >+ <option value="debit">{t('rules.typeExpense')}</option>+ <option value="credit">{t('rules.typeIncome')}</option>+ </select>+ ) : cond.field === 'account_id' ? (+ <select+ className={`${selectClass} w-0 flex-1 min-w-0`}+ value={String(cond.value)}+ onChange={(e) => updateCondition(i, 'value', e.target.value)}+ >+ <option value="">{t('rules.selectAccount')}</option>+ {accounts.map(acc => (+ <option key={acc.id} value={acc.id}>{getAccountName(acc)}</option>+ ))}+ </select>+ ) : cond.field === 'payee_id' ? (+ <select+ className={`${selectClass} w-0 flex-1 min-w-0`}+ value={String(cond.value)}+ onChange={(e) => updateCondition(i, 'value', e.target.value)}+ >+ <option value="">{t('rules.selectPayee')}</option>+ {payees.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ ) : (+ <Input+ className="w-0 flex-1 min-w-0 h-8 text-sm"+ value={String(cond.value)}+ onChange={(e) => updateCondition(i, 'value', e.target.value)}+ placeholder={cond.field === 'amount' ? '0.00' : cond.field === 'date' ? 'YYYY-MM-DD' : t('rules.valuePlaceholder')}+ type={cond.field === 'amount' ? 'number' : cond.field === 'date' ? 'date' : 'text'}+ />+ )}+ <button+ type="button"+ className="p-1 text-muted-foreground hover:text-rose-500 transition-colors shrink-0"+ onClick={() => removeCondition(i)}+ >+ <X size={13} />+ </button>+ </div>+ ))}+ <button+ type="button"+ className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"+ onClick={addCondition}+ >+ <Plus size={12} /> {t('rules.addCondition')}+ </button>+ </div>+ </div>++ {/* Actions */}+ <div className="space-y-2">+ <Label>{t('rules.actions')}</Label>+ <div className="space-y-2">+ {actions.map((action, i) => (+ <div key={i} className="flex items-center gap-2 min-w-0">+ <select+ className={`${selectClass} w-40 shrink-0`}+ value={action.op}+ onChange={(e) => updateAction(i, 'op', e.target.value)}+ >+ <option value="set_category">{t('rules.setCategory')}</option>+ <option value="set_payee">{t('rules.setPayee')}</option>+ <option value="append_notes">{t('rules.appendNotes')}</option>+ <option value="ignore">{t('rules.ignoreAction')}</option>+ </select>+ {action.op === 'ignore' ? (+ <span className="w-0 flex-1 min-w-0 text-sm text-muted-foreground italic">+ {t('rules.ignoreActionHint')}+ </span>+ ) : action.op === 'set_category' ? (+ <div className="w-0 flex-1 min-w-0">+ <CategorySelect+ value={action.value}+ onChange={(val) => updateAction(i, 'value', val)}+ categories={categories}+ groups={categoryGroups}+ placeholder={t('rules.selectCategory')}+ className={`${selectClass} w-full`}+ />+ </div>+ ) : action.op === 'set_payee' ? (+ <select+ className={`${selectClass} w-0 flex-1 min-w-0`}+ value={action.value}+ onChange={(e) => updateAction(i, 'value', e.target.value)}+ required+ >+ <option value="">{t('rules.selectPayee')}</option>+ {payees.map(p => (+ <option key={p.id} value={p.id}>{p.name}</option>+ ))}+ </select>+ ) : (+ <Input+ className="w-0 flex-1 min-w-0 h-8 text-sm"+ value={action.value}+ onChange={(e) => updateAction(i, 'value', e.target.value)}+ placeholder="Ex: #work #reimbursable"+ />+ )}+ <button+ type="button"+ className="p-1 text-muted-foreground hover:text-rose-500 transition-colors shrink-0"+ onClick={() => removeAction(i)}+ >+ <X size={13} />+ </button>+ </div>+ ))}+ <button+ type="button"+ className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"+ onClick={addAction}+ >+ <Plus size={12} /> {t('rules.addAction')}+ </button>+ </div>+ </div>++ {/* Active toggle */}+ <label className="flex items-center gap-2 cursor-pointer">+ <input+ type="checkbox"+ checked={isActive}+ onChange={(e) => setIsActive(e.target.checked)}+ className="h-4 w-4 rounded border-border"+ />+ <span className="text-sm text-foreground">{t('rules.ruleActive')}</span>+ </label>++ <DialogFooter>+ <Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button>+ <Button type="submit" disabled={loading}>+ {loading ? t('common.loading') : t('common.save')}+ </Button>+ </DialogFooter>+ </form>+ </DialogContent>+ </Dialog>+ )+}diff --git a/frontend/src/components/transaction-dialog.tsx b/frontend/src/components/transaction-dialog.tsxindex f09d9403..6ea37c25 100644--- a/frontend/src/components/transaction-dialog.tsx+++ b/frontend/src/components/transaction-dialog.tsx@@ -16,7 +16,7 @@ import {DialogTitle,DialogFooter,} from '@/components/ui/dialog'-import { AlertTriangle, ChevronDown, ChevronLeft, Download, Eye, EyeClosed, Paperclip, Upload, X, FileText, Plus, Unlink } from 'lucide-react'+import { AlertTriangle, ChevronDown, ChevronLeft, Download, Eye, EyeClosed, Paperclip, Upload, X, FileText, Plus, Unlink, SlidersHorizontal } from 'lucide-react'import {DropdownMenu,DropdownMenuContent,@@ -72,6 +72,7 @@ export function TransactionDialog({onDelete,onUnlinkTransfer,onIgnoreChanged,+ onCreateRule,loading,error,isSynced = false,@@ -89,6 +90,7 @@ export function TransactionDialog({onDelete?: () => voidonUnlinkTransfer?: (pairId: string) => voidonIgnoreChanged?: () => void+ onCreateRule?: (tx: Transaction) => voidloading: booleanerror: string | nullisSynced?: boolean@@ -160,6 +162,7 @@ export function TransactionDialog({onDelete={onDelete}onUnlinkTransfer={onUnlinkTransfer}onIgnoreChanged={onIgnoreChanged}+ onCreateRule={onCreateRule}onCancel={onClose}loading={loading}error={error}@@ -277,6 +280,7 @@ function TransactionForm({onDelete,onUnlinkTransfer,onIgnoreChanged,+ onCreateRule,onCancel,loading,error,@@ -295,6 +299,7 @@ function TransactionForm({onDelete?: () => voidonUnlinkTransfer?: (pairId: string) => voidonIgnoreChanged?: () => void+ onCreateRule?: (tx: Transaction) => voidonCancel: () => voidloading: booleanerror: string | null@@ -874,6 +879,18 @@ function TransactionForm({{isIgnored ? t('transactions.unignoreAction') : t('transactions.ignoreAction')}</Button>)}+ {transaction && onCreateRule && (+ <Button+ type="button"+ variant="outline"+ onClick={() => onCreateRule(transaction)}+ className="gap-1.5"+ title={t('transactions.createRule')}+ >+ <SlidersHorizontal size={16} />+ {t('transactions.createRule')}+ </Button>+ )}</div><div className="flex gap-2"><Button type="button" variant="outline" onClick={onCancel}>diff --git a/frontend/src/locales/en.json b/frontend/src/locales/en.jsonindex 7e50e7fc..237ef8cd 100644--- a/frontend/src/locales/en.json+++ b/frontend/src/locales/en.json@@ -233,6 +233,7 @@"noCategory": "No category","addManual": "Add Transaction","duplicate": "Duplicate",+ "createRule": "Create Rule","saveAndNew": "Save & New","saveAndDuplicate": "Save & Duplicate","moreSaveOptions": "More save options",diff --git a/frontend/src/locales/es.json b/frontend/src/locales/es.jsonindex 887e0f50..c1e4854d 100644--- a/frontend/src/locales/es.json+++ b/frontend/src/locales/es.json@@ -231,6 +231,7 @@"noCategory": "Sin categoría","addManual": "Agregar transacción","duplicate": "Duplicar",+ "createRule": "Crear regla","saveAndNew": "Guardar y nuevo","saveAndDuplicate": "Guardar y duplicar","moreSaveOptions": "Más opciones de guardado",diff --git a/frontend/src/locales/pt-BR.json b/frontend/src/locales/pt-BR.jsonindex 61a39388..41d22bb8 100644--- a/frontend/src/locales/pt-BR.json+++ b/frontend/src/locales/pt-BR.json@@ -233,6 +233,7 @@"noCategory": "Sem categoria","addManual": "Adicionar Transação","duplicate": "Duplicar",+ "createRule": "Criar Regra","saveAndNew": "Salvar e novo","saveAndDuplicate": "Salvar e duplicar","moreSaveOptions": "Mais opções de salvar",diff --git a/frontend/src/pages/rules.tsx b/frontend/src/pages/rules.tsxindex 071c674a..8c616c54 100644--- a/frontend/src/pages/rules.tsx+++ b/frontend/src/pages/rules.tsx@@ -1,26 +1,23 @@import { useState, useMemo } from 'react'-import { getAccountName } from '@/lib/account-utils'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'import { categories as categoriesApi, categoryGroups as categoryGroupsApi, rules as rulesApi, accounts as accountsApi, payees as payeesApi } from '@/lib/api'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Button } from '@/components/ui/button'-import { Input } from '@/components/ui/input'import { Label } from '@/components/ui/label'import {Dialog,DialogContent,DialogHeader,DialogTitle,- DialogFooter,} from '@/components/ui/dialog'-import type { Category, CategoryGroup, Payee, Rule, RuleCondition, RuleAction } from '@/types'-import { Trash2, Plus, RefreshCw, X, Package, Check, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'+import type { Category, Payee, Rule, RuleAction, RuleCondition } from '@/types'+import { Trash2, Plus, RefreshCw, Package, Check, ArrowUpDown, ArrowUp, ArrowDown } from 'lucide-react'import { cn } from '@/lib/utils'-import { CategorySelect } from '@/components/category-select'import { PageHeader } from '@/components/page-header'import { useWorkspace } from '@/contexts/workspace-context'+import { RuleDialog } from '@/components/rule-dialog'function SectionCard({ children }: { children: React.ReactNode }) {return (@@ -460,276 +457,3 @@ function RulePacksDialog({ open, onClose }: { open: boolean; onClose: () => void)}-function RuleDialog({- open, onClose, rule, categories, categoryGroups, accounts, payees, onSave, loading,-}: {- open: boolean- onClose: () => void- rule: Rule | null- categories: Category[]- categoryGroups: CategoryGroup[]- accounts: { id: string; name: string }[]- payees: Payee[]- onSave: (data: Partial<Rule>) => void- loading: boolean-}) {- const { t } = useTranslation()- const [name, setName] = useState(rule?.name ?? '')- const [conditionsOp, setConditionsOp] = useState<'and' | 'or'>(rule?.conditions_op ?? 'and')- const [conditions, setConditions] = useState<RuleCondition[]>(- rule?.conditions?.length ? rule.conditions as RuleCondition[] : [{ field: 'description', op: 'contains', value: '' }]- )- const [actions, setActions] = useState<RuleAction[]>(- rule?.actions?.length ? rule.actions as RuleAction[] : [{ op: 'set_category', value: '' }]- )- const [priority, setPriority] = useState(rule?.priority ?? 0)- const [isActive, setIsActive] = useState(rule?.is_active ?? true)-- const selectClass = 'border border-border rounded-lg px-2 py-1.5 text-sm bg-card text-foreground focus:outline-none focus:ring-2 focus:ring-primary'-- function updateCondition(i: number, field: keyof RuleCondition, val: string | number) {- setConditions(prev => prev.map((c, idx) => idx === i ? { ...c, [field]: val } : c))- }-- function removeCondition(i: number) {- setConditions(prev => prev.filter((_, idx) => idx !== i))- }-- function addCondition() {- setConditions(prev => [...prev, { field: 'description', op: 'contains', value: '' }])- }-- function updateAction(i: number, field: keyof RuleAction, val: string) {- setActions(prev => prev.map((a, idx) => {- if (idx !== i) return a- const next = { ...a, [field]: val }- // Switching op clears any stale value (e.g. category UUID → ignore).- if (field === 'op') next.value = ''- return next- }))- }-- function removeAction(i: number) {- setActions(prev => prev.filter((_, idx) => idx !== i))- }-- function addAction() {- setActions(prev => [...prev, { op: 'set_category', value: '' }])- }-- function handleSubmit(e: React.FormEvent) {- e.preventDefault()- onSave({ name, conditions_op: conditionsOp, conditions, actions, priority, is_active: isActive })- }-- return (- <Dialog open={open} onOpenChange={onClose}>- <DialogContent className="max-w-2xl max-h-[90vh] overflow-y-auto overflow-x-hidden">- <DialogHeader>- <DialogTitle>{rule ? t('rules.editRule') : t('rules.newRule')}</DialogTitle>- </DialogHeader>- <form key={rule?.id ?? 'new'} onSubmit={handleSubmit} className="space-y-5">- {/* Name + Priority */}- <div className="grid grid-cols-3 gap-3">- <div className="col-span-2 space-y-1.5">- <Label>{t('rules.name')}</Label>- <Input value={name} onChange={(e) => setName(e.target.value)} required placeholder="Ex: Uber" />- </div>- <div className="space-y-1.5">- <Label>{t('rules.priority')}</Label>- <Input type="number" value={priority} onChange={(e) => setPriority(Number(e.target.value))} />- </div>- </div>-- {/* Conditions */}- <div className="space-y-2">- <div className="flex items-center justify-between">- <Label>{t('rules.conditions')}</Label>- <div className="flex items-center gap-1 bg-muted rounded-lg p-0.5">- {(['and', 'or'] as const).map(op => (- <button- key={op}- type="button"- className={cn(- 'px-3 py-1 text-xs font-semibold rounded-md transition-all',- conditionsOp === op ? 'bg-card shadow-sm text-foreground' : 'text-muted-foreground hover:text-foreground'- )}- onClick={() => setConditionsOp(op)}- >- {op === 'and' ? t('rules.andOp') : t('rules.orOp')}- </button>- ))}- </div>- </div>- <div className="space-y-2">- {conditions.map((cond, i) => (- <div key={i} className="flex items-center gap-2 min-w-0">- <select- className={`${selectClass} w-32 shrink-0`}- value={cond.field}- onChange={(e) => updateCondition(i, 'field', e.target.value)}- >- {CONDITION_FIELDS.map(f => (- <option key={f.value} value={f.value}>{t(f.label)}</option>- ))}- </select>- <select- className={`${selectClass} w-32 shrink-0`}- value={cond.op}- onChange={(e) => updateCondition(i, 'op', e.target.value)}- >- {getOpsForField(cond.field).map(o => (- <option key={o.value} value={o.value}>{t(o.label)}</option>- ))}- </select>- {cond.field === 'type' ? (- <select- className={`${selectClass} w-0 flex-1 min-w-0`}- value={String(cond.value)}- onChange={(e) => updateCondition(i, 'value', e.target.value)}- >- <option value="debit">{t('rules.typeExpense')}</option>- <option value="credit">{t('rules.typeIncome')}</option>- </select>- ) : cond.field === 'account_id' ? (- <select- className={`${selectClass} w-0 flex-1 min-w-0`}- value={String(cond.value)}- onChange={(e) => updateCondition(i, 'value', e.target.value)}- >- <option value="">{t('rules.selectAccount')}</option>- {accounts.map(acc => (- <option key={acc.id} value={acc.id}>{getAccountName(acc)}</option>- ))}- </select>- ) : cond.field === 'payee_id' ? (- <select- className={`${selectClass} w-0 flex-1 min-w-0`}- value={String(cond.value)}- onChange={(e) => updateCondition(i, 'value', e.target.value)}- >- <option value="">{t('rules.selectPayee')}</option>- {payees.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- ) : (- <Input- className="w-0 flex-1 min-w-0 h-8 text-sm"- value={String(cond.value)}- onChange={(e) => updateCondition(i, 'value', e.target.value)}- placeholder={cond.field === 'amount' ? '0.00' : cond.field === 'date' ? 'YYYY-MM-DD' : t('rules.valuePlaceholder')}- type={cond.field === 'amount' ? 'number' : cond.field === 'date' ? 'date' : 'text'}- />- )}- <button- type="button"- className="p-1 text-muted-foreground hover:text-rose-500 transition-colors shrink-0"- onClick={() => removeCondition(i)}- >- <X size={13} />- </button>- </div>- ))}- <button- type="button"- className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"- onClick={addCondition}- >- <Plus size={12} /> {t('rules.addCondition')}- </button>- </div>- </div>-- {/* Actions */}- <div className="space-y-2">- <Label>{t('rules.actions')}</Label>- <div className="space-y-2">- {actions.map((action, i) => (- <div key={i} className="flex items-center gap-2 min-w-0">- <select- className={`${selectClass} w-40 shrink-0`}- value={action.op}- onChange={(e) => updateAction(i, 'op', e.target.value)}- >- <option value="set_category">{t('rules.setCategory')}</option>- <option value="set_payee">{t('rules.setPayee')}</option>- <option value="append_notes">{t('rules.appendNotes')}</option>- <option value="ignore">{t('rules.ignoreAction')}</option>- </select>- {action.op === 'ignore' ? (- <span className="w-0 flex-1 min-w-0 text-sm text-muted-foreground italic">- {t('rules.ignoreActionHint')}- </span>- ) : action.op === 'set_category' ? (- <div className="w-0 flex-1 min-w-0">- <CategorySelect- value={action.value}- onChange={(val) => updateAction(i, 'value', val)}- categories={categories}- groups={categoryGroups}- placeholder={t('rules.selectCategory')}- className={`${selectClass} w-full`}- />- </div>- ) : action.op === 'set_payee' ? (- <select- className={`${selectClass} w-0 flex-1 min-w-0`}- value={action.value}- onChange={(e) => updateAction(i, 'value', e.target.value)}- required- >- <option value="">{t('rules.selectPayee')}</option>- {payees.map(p => (- <option key={p.id} value={p.id}>{p.name}</option>- ))}- </select>- ) : (- <Input- className="w-0 flex-1 min-w-0 h-8 text-sm"- value={action.value}- onChange={(e) => updateAction(i, 'value', e.target.value)}- placeholder="Ex: #work #reimbursable"- />- )}- <button- type="button"- className="p-1 text-muted-foreground hover:text-rose-500 transition-colors shrink-0"- onClick={() => removeAction(i)}- >- <X size={13} />- </button>- </div>- ))}- <button- type="button"- className="text-xs text-primary hover:text-primary/80 font-medium flex items-center gap-1"- onClick={addAction}- >- <Plus size={12} /> {t('rules.addAction')}- </button>- </div>- </div>-- {/* Active toggle */}- <label className="flex items-center gap-2 cursor-pointer">- <input- type="checkbox"- checked={isActive}- onChange={(e) => setIsActive(e.target.checked)}- className="h-4 w-4 rounded border-border"- />- <span className="text-sm text-foreground">{t('rules.ruleActive')}</span>- </label>-- <DialogFooter>- <Button type="button" variant="outline" onClick={onClose}>{t('common.cancel')}</Button>- <Button type="submit" disabled={loading}>- {loading ? t('common.loading') : t('common.save')}- </Button>- </DialogFooter>- </form>- </DialogContent>- </Dialog>- )-}diff --git a/frontend/src/pages/transactions.tsx b/frontend/src/pages/transactions.tsxindex 15ea6d62..d39f66d2 100644--- a/frontend/src/pages/transactions.tsx+++ b/frontend/src/pages/transactions.tsx@@ -6,7 +6,7 @@ import { MonthStepper } from '@/components/month-stepper'import { useNavigate, useSearchParams } from 'react-router-dom'import { useTranslation } from 'react-i18next'import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'-import { transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi, accounts as accountsApi, recurring, payees as payeesApi, admin, groups as groupsApi } from '@/lib/api'+import { transactions, categories as categoriesApi, categoryGroups as categoryGroupsApi, accounts as accountsApi, recurring, payees as payeesApi, admin, groups as groupsApi, rules as rulesApi } from '@/lib/api'import { invalidateFinancialQueries } from '@/lib/invalidate-queries'import { toast } from 'sonner'import { Button } from '@/components/ui/button'@@ -26,8 +26,9 @@ import {TableRow,} from '@/components/ui/table'import { Skeleton } from '@/components/ui/skeleton'-import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Copy, Download, HelpCircle, Info, Paperclip, Users, X, EyeClosed } from 'lucide-react'-import type { Transaction } from '@/types'+import { AlertTriangle, ArrowLeftRight, ArrowUp, ArrowDown, Check, Copy, Download, HelpCircle, Info, Paperclip, Users, X, EyeClosed, SlidersHorizontal } from 'lucide-react'+import type { Transaction, Rule } from '@/types'+import { RuleDialog, type RuleDialogInitialData } from '@/components/rule-dialog'import { PageHeader } from '@/components/page-header'import { CategoryIcon } from '@/components/category-icon'import { CategorySelect } from '@/components/category-select'@@ -156,6 +157,8 @@ export default function TransactionsPage() {const [bulkCategory, setBulkCategory] = useState<string>('')const [bulkAddToGroupOpen, setBulkAddToGroupOpen] = useState(false)const [bulkTagInput, setBulkTagInput] = useState<string>('')+ const [createRuleOpen, setCreateRuleOpen] = useState(false)+ const [createRuleInitialData, setCreateRuleInitialData] = useState<RuleDialogInitialData | undefined>(undefined)const debounceRef = useRef<ReturnType<typeof setTimeout>>(null)const highlightId = searchParams.get('highlight')const highlightedRowRef = useRef<HTMLTableRowElement | null>(null)@@ -557,6 +560,42 @@ export default function TransactionsPage() {},})+ const createRuleMutation = useMutation({+ mutationFn: (data: Omit<Rule, 'id' | 'user_id'>) => rulesApi.create(data),+ onSuccess: () => {+ queryClient.invalidateQueries({ queryKey: ['rules'] })+ setCreateRuleOpen(false)+ setCreateRuleInitialData(undefined)+ toast.success(t('rules.created'))+ },+ onError: (error: unknown) => {+ const err = error as { response?: { status?: number } }+ if (err?.response?.status === 409) {+ toast.error(t('rules.duplicateName'))+ } else {+ toast.error(t('common.error'))+ }+ },+ })++ const handleCreateRuleFromTransaction = (tx: Transaction) => {+ const conditions = [+ { field: 'description', op: 'contains', value: tx.description },+ ]+ if (tx.payee_id) {+ conditions.push({ field: 'payee_id', op: 'equals', value: tx.payee_id })+ }+ const actions: { op: string; value: string }[] = tx.category_id+ ? [{ op: 'set_category', value: tx.category_id }]+ : [{ op: 'set_category', value: '' }]+ const tags = parseHashtags(tx.notes)+ if (tags.length > 0) {+ actions.push({ op: 'append_notes', value: tags.join(' ') })+ }+ setCreateRuleInitialData({ conditions, actions })+ setCreateRuleOpen(true)+ }+const toggleSelect = (id: string) => {setSelectedIds(prev => {const next = new Set(prev)@@ -1427,6 +1466,26 @@ export default function TransactionsPage() {<span className="hidden lg:inline">{t('transactions.linkAsTransfer')}</span></Button>+ <div className="w-px bg-border/60 self-stretch" />++ {/* Create Rule — only when exactly one non-shared transaction is selected */}+ {selectedIds.size === 1 && (() => {+ const selectedTx = filteredItems.find(tx => selectedIds.has(tx.id))+ if (!selectedTx || selectedTx.is_shared) return null+ return (+ <Button+ size="sm"+ variant="ghost"+ onClick={() => handleCreateRuleFromTransaction(selectedTx)}+ className="h-8 px-3 shrink-0 text-sm"+ title={t('transactions.createRule')}+ >+ <SlidersHorizontal size={15} className="lg:mr-1.5" />+ <span className="hidden lg:inline">{t('transactions.createRule')}</span>+ </Button>+ )+ })()}+<div className="ml-auto" />{/* Close */}@@ -1502,6 +1561,11 @@ export default function TransactionsPage() {onDelete={editingTx ? () => deleteMutation.mutate(editingTx.id) : undefined}onUnlinkTransfer={(pairId) => unlinkTransferMutation.mutate(pairId)}onIgnoreChanged={invalidateAfterTxMutation}+ onCreateRule={(tx) => {+ setDialogOpen(false)+ setEditingTx(null)+ handleCreateRuleFromTransaction(tx)+ }}loading={createMutation.isPending || updateMutation.isPending || deleteMutation.isPending || unlinkTransferMutation.isPending}error={createMutation.error || updateMutation.error ? extractApiError(createMutation.error || updateMutation.error) : null}isSynced={editingTx?.source === 'sync'}@@ -1548,6 +1612,21 @@ export default function TransactionsPage() {</DialogFooter></DialogContent></Dialog>++ {/* Create Rule from Transaction Dialog */}+ <RuleDialog+ key={createRuleOpen ? 'rule-open' : 'rule-closed'}+ open={createRuleOpen}+ onClose={() => { setCreateRuleOpen(false); setCreateRuleInitialData(undefined) }}+ rule={null}+ categories={categoriesList ?? []}+ categoryGroups={categoryGroupsList ?? []}+ accounts={accountsList ?? []}+ payees={payeesList ?? []}+ onSave={(data) => createRuleMutation.mutate(data as Omit<Rule, 'id' | 'user_id'>)}+ loading={createRuleMutation.isPending}+ initialData={createRuleInitialData}+ /></div>)}