Skip to content

A local-first personal finance app

[AI] Drag-and-drop reordering for upcoming scheduled transactions (#8385)

Stephen Brown II5be2449354ba
diff --git a/packages/desktop-client/src/components/transactions/TransactionList.tsx b/packages/desktop-client/src/components/transactions/TransactionList.tsx
index f15c275a18..d04ff1dab2 100644
--- a/packages/desktop-client/src/components/transactions/TransactionList.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionList.tsx
@@ -630,6 +630,46 @@ export function TransactionList({
return;
}
+ // Preview (upcoming schedule) reordering: only against other
+ // previews on the same date. Never mix preview and real transactions.
+ if (isPreviewId(id) !== isPreviewId(targetId)) {
+ return;
+ }
+ if (isPreviewId(id)) {
+ const targetTrans = allTransactions.find(t => t.id === targetId);
+ if (!targetTrans || targetTrans.date !== draggedTrans.date) {
+ return;
+ }
+
+ const previews = allTransactions.filter(
+ t => isPreviewId(t.id) && t.date === draggedTrans.date,
+ );
+ const targetIdx = previews.findIndex(t => t.id === targetId);
+ if (targetIdx === -1) {
+ return;
+ }
+
+ let apiTargetId: string | null;
+ if (dropPos === 'after') {
+ apiTargetId = targetTrans.schedule ?? null;
+ } else {
+ const aboveIdx = targetIdx - 1;
+ apiTargetId =
+ aboveIdx >= 0 ? (previews[aboveIdx].schedule ?? null) : null;
+ }
+
+ if (!draggedTrans.schedule) {
+ return;
+ }
+
+ await send('schedule/move', {
+ id: draggedTrans.schedule,
+ targetId: apiTargetId,
+ });
+ onRefetch();
+ return;
+ }
+
// Child transaction reordering: siblings only
if (draggedTrans.is_child && draggedTrans.parent_id) {
const siblings = allTransactions.filter(
diff --git a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
index 3ca4202a91..78a5918c92 100644
--- a/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
+++ b/packages/desktop-client/src/components/transactions/TransactionsTable.tsx
@@ -969,6 +969,7 @@ type TransactionProps = {
draggedId?: TransactionEntity['id'] | null;
draggedParentId?: TransactionEntity['parent_id'] | null;
siblingCount?: number;
+ previewSiblingCount?: number;
prevRowDate?: string | null;
nextRowDate?: string | null;
sortField?: string;
@@ -1026,6 +1027,7 @@ const Transaction = memo(function Transaction({
draggedId,
draggedParentId,
siblingCount = 0,
+ previewSiblingCount = 0,
prevRowDate,
nextRowDate,
sortField,
@@ -1336,16 +1338,19 @@ const Transaction = memo(function Transaction({
const parentId = transaction.parent_id;
// Disable drag if this is the only transaction on its date (nothing to reorder with)
// For child transactions, disable if there's only one sibling (nothing to reorder with)
+ // For previews, disable if there's only one preview on this date (real transactions
+ // sharing the date don't count; previews can only reorder against other previews)
const isOnlyTransactionOnDate = isChildTransaction
? siblingCount <= 1
- : prevRowDate !== transaction.date && nextRowDate !== transaction.date;
+ : isPreview
+ ? previewSiblingCount <= 1
+ : prevRowDate !== transaction.date && nextRowDate !== transaction.date;
const previewRef = useRef<DragPreviewRenderer>(null);
// Row-level drag must not compete with inline editors (notes, amounts,
// payee, etc.): otherwise clicks/drags inside inputs start a reorder drag
// instead of moving the caret or selecting text (see GH #7567).
const allowRowDrag =
canDrag &&
- !isPreview &&
!isOnlyTransactionOnDate &&
(!editing || focusedField === 'select' || focusedField === 'cleared');
const { dragRef, dragProps } = useDrag<TransactionEntity>({
@@ -1358,14 +1363,22 @@ const Transaction = memo(function Transaction({
// Gate callbacks for non-reorderable rows (children/previews) to avoid invalid drop operations
// For child transactions, allow drops only from siblings (same parent)
+ // For previews, allow drops only from another preview on the same date
+ const draggedIsPreview = draggedId != null && isPreviewId(draggedId);
const isSiblingDrag = isChildTransaction && draggedParentId === parentId;
+ const isSiblingPreviewDrag =
+ isPreview && draggedIsPreview && draggedDate === transaction.date;
const safeOnDrop: OnDropCallback | undefined = isPreview
- ? undefined
- : isChildTransaction
- ? isSiblingDrag
- ? onDrop
- : undefined
- : onDrop;
+ ? isSiblingPreviewDrag
+ ? onDrop
+ : undefined
+ : draggedIsPreview
+ ? undefined
+ : isChildTransaction
+ ? isSiblingDrag
+ ? onDrop
+ : undefined
+ : onDrop;
const { dropRef, dropProps, dropPos } = useDrop<TransactionEntity>({
types: 'transaction',
@@ -1378,8 +1391,12 @@ const Transaction = memo(function Transaction({
// Check if this row is a valid drop target for the currently dragged transaction
const isValidDropTarget = useMemo(() => {
- // Non-droppable row types
- if (isPreview) return false;
+ // Previews can only be valid drop targets for other previews on the
+ // same date. Never mix preview and real transactions.
+ if (isPreview !== draggedIsPreview) return false;
+ if (isPreview) {
+ return draggedDate === transaction.date && dropPos != null;
+ }
// When dragging a child transaction, only siblings are valid targets
if (draggedParentId) {
@@ -1414,6 +1431,7 @@ const Transaction = memo(function Transaction({
}, [
draggedDate,
draggedParentId,
+ draggedIsPreview,
parentId,
isChildTransaction,
isPreview,
@@ -2638,6 +2656,13 @@ function TransactionTableInner({
? (props.transactionsByParent[trans.parent_id]?.length ?? 0)
: 0;
+ // Get preview sibling count on the same date (used for drag/drop)
+ const previewSiblingCount = isPreviewId(trans.id)
+ ? props.transactions.filter(
+ t => isPreviewId(t.id) && t.date === trans.date,
+ ).length
+ : 0;
+
// Compute adjacent row dates for boundary drop detection
// Use transactionsToRender (filtered list) to match rendered row indices
// Skip non-reorderable rows (child/preview) when finding neighbors
@@ -2721,6 +2746,7 @@ function TransactionTableInner({
draggedParentId={props.draggedParentId}
draggedDate={props.draggedDate}
siblingCount={siblingCount}
+ previewSiblingCount={previewSiblingCount}
prevRowDate={prevRowDate}
nextRowDate={nextRowDate}
sortField={props.sortField}
diff --git a/packages/desktop-client/src/hooks/usePreviewTransactions.test.ts b/packages/desktop-client/src/hooks/usePreviewTransactions.test.ts
new file mode 100644
index 0000000000..817cd0ff27
--- /dev/null
+++ b/packages/desktop-client/src/hooks/usePreviewTransactions.test.ts
@@ -0,0 +1,33 @@
+import { describe, expect, test } from 'vitest';
+
+import { comparePreviewTransactions } from './usePreviewTransactions';
+
+describe('comparePreviewTransactions', () => {
+ test('sorts by date descending first', () => {
+ const a = { date: '2024-01-01', amount: 100, sort_order: 0 };
+ const b = { date: '2024-01-05', amount: 100, sort_order: 0 };
+ expect(comparePreviewTransactions(a, b)).toBeGreaterThan(0);
+ expect(comparePreviewTransactions(b, a)).toBeLessThan(0);
+ });
+
+ test('same date: sorts by sort_order descending', () => {
+ const a = { date: '2024-01-01', amount: 100, sort_order: 5 };
+ const b = { date: '2024-01-01', amount: 100, sort_order: 10 };
+ expect(comparePreviewTransactions(a, b)).toBeGreaterThan(0);
+ expect(comparePreviewTransactions(b, a)).toBeLessThan(0);
+ });
+
+ test('same date, null/equal sort_order: falls back to amount ascending', () => {
+ const a = { date: '2024-01-01', amount: 200, sort_order: null };
+ const b = { date: '2024-01-01', amount: 100, sort_order: null };
+ expect(comparePreviewTransactions(a, b)).toBeGreaterThan(0);
+ expect(comparePreviewTransactions(b, a)).toBeLessThan(0);
+ });
+
+ test('same date, one sort_order undefined treated as 0', () => {
+ const a = { date: '2024-01-01', amount: 100, sort_order: undefined };
+ const b = { date: '2024-01-01', amount: 999, sort_order: 5 };
+ // b has higher sort_order (5 > 0), so b sorts first regardless of amount
+ expect(comparePreviewTransactions(a, b)).toBeGreaterThan(0);
+ });
+});
diff --git a/packages/desktop-client/src/hooks/usePreviewTransactions.ts b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
index f0526e9bd5..5d63b32dcb 100644
--- a/packages/desktop-client/src/hooks/usePreviewTransactions.ts
+++ b/packages/desktop-client/src/hooks/usePreviewTransactions.ts
@@ -36,6 +36,25 @@ type UsePreviewTransactionsResult = {
error?: Error;
};
+export function comparePreviewTransactions(
+ a: Pick<TransactionEntity, 'date' | 'amount'> & {
+ sort_order?: number | null;
+ },
+ b: Pick<TransactionEntity, 'date' | 'amount'> & {
+ sort_order?: number | null;
+ },
+): number {
+ const dateDiff =
+ monthUtils.parseDate(b.date).getTime() -
+ monthUtils.parseDate(a.date).getTime();
+ if (dateDiff !== 0) return dateDiff;
+
+ const sortOrderDiff = (b.sort_order ?? 0) - (a.sort_order ?? 0);
+ if (sortOrderDiff !== 0) return sortOrderDiff;
+
+ return a.amount - b.amount;
+}
+
export function usePreviewTransactions({
filter,
options,
@@ -88,10 +107,15 @@ export function usePreviewTransactions({
)
.then(newTrans => {
if (!isUnmounted) {
+ const scheduleById = new Map(schedules.map(s => [s.id, s]));
const withDefaults = newTrans.map(t => ({
...t,
category: t.schedule != null ? statuses.get(t.schedule) : undefined,
schedule: t.schedule,
+ sort_order:
+ t.schedule != null
+ ? scheduleById.get(t.schedule)?.sort_order
+ : undefined,
subtransactions: t.subtransactions?.map(
(st: TransactionEntity) => ({
...st,
@@ -102,11 +126,7 @@ export function usePreviewTransactions({
}));
// re-sort in case rule actions have changed the dates
- withDefaults.sort(
- (a, b) =>
- monthUtils.parseDate(b.date).getTime() -
- monthUtils.parseDate(a.date).getTime() || a.amount - b.amount,
- );
+ withDefaults.sort(comparePreviewTransactions);
const ungroupedTransactions = ungroupTransactions(withDefaults);
setPreviewTransactions(ungroupedTransactions);
diff --git a/packages/loot-core/migrations/1783004650757_schedule_sort_order.sql b/packages/loot-core/migrations/1783004650757_schedule_sort_order.sql
new file mode 100644
index 0000000000..f5d00ff6ed
--- /dev/null
+++ b/packages/loot-core/migrations/1783004650757_schedule_sort_order.sql
@@ -0,0 +1,5 @@
+BEGIN TRANSACTION;
+
+ALTER TABLE schedules ADD COLUMN sort_order REAL DEFAULT 0;
+
+COMMIT;
diff --git a/packages/loot-core/src/server/aql/schema/index.ts b/packages/loot-core/src/server/aql/schema/index.ts
index 746ec602a1..cb5e4710b0 100644
--- a/packages/loot-core/src/server/aql/schema/index.ts
+++ b/packages/loot-core/src/server/aql/schema/index.ts
@@ -113,6 +113,7 @@ export const schema = {
posts_transaction: f('boolean'),
custom_upcoming_length: f('string'),
tombstone: f('boolean'),
+ sort_order: f('float'),
// These are special fields that are actually pulled from the
// underlying rule
diff --git a/packages/loot-core/src/server/budget/template-notes.test.ts b/packages/loot-core/src/server/budget/template-notes.test.ts
index 0857ac15f4..bfcdb7984d 100644
--- a/packages/loot-core/src/server/budget/template-notes.test.ts
+++ b/packages/loot-core/src/server/budget/template-notes.test.ts
@@ -379,6 +379,7 @@ function mockSchedules(): db.DbSchedule[] {
tombstone: 0,
name: 'Mock Schedule 1',
custom_upcoming_length: null,
+ sort_order: 0,
},
{
id: 'mock-schedule-2',
@@ -389,6 +390,7 @@ function mockSchedules(): db.DbSchedule[] {
tombstone: 0,
name: 'Mock Schedule 2',
custom_upcoming_length: null,
+ sort_order: 0,
},
];
}
diff --git a/packages/loot-core/src/server/db/index.test.ts b/packages/loot-core/src/server/db/index.test.ts
index e8404e59ca..1c2f3bdc98 100644
--- a/packages/loot-core/src/server/db/index.test.ts
+++ b/packages/loot-core/src/server/db/index.test.ts
@@ -140,6 +140,38 @@ describe('Database', () => {
expect(await getTransactions('2018-01-05')).toMatchSnapshot();
});
+ test('schedules can be reordered', async () => {
+ await db.insertWithUUID('schedules', { id: 'sched1', sort_order: 30 });
+ await db.insertWithUUID('schedules', { id: 'sched2', sort_order: 20 });
+ await db.insertWithUUID('schedules', { id: 'sched3', sort_order: 10 });
+
+ // Move sched3 (currently last) to be right after sched1 (currently first)
+ await db.moveSchedule('sched3', 'sched1');
+
+ const rows = await db.all<{ id: string; sort_order: number }>(
+ 'SELECT id, sort_order FROM schedules ORDER BY sort_order DESC, id',
+ );
+ expect(rows.map(r => r.id)).toEqual(['sched1', 'sched3', 'sched2']);
+ });
+
+ test('moving a schedule to the top uses a null targetId', async () => {
+ await db.insertWithUUID('schedules', { id: 'sched1', sort_order: 30 });
+ await db.insertWithUUID('schedules', { id: 'sched2', sort_order: 20 });
+
+ await db.moveSchedule('sched2', null);
+
+ const rows = await db.all<{ id: string; sort_order: number }>(
+ 'SELECT id, sort_order FROM schedules ORDER BY sort_order DESC, id',
+ );
+ expect(rows.map(r => r.id)).toEqual(['sched2', 'sched1']);
+ });
+
+ test('moving a non-existent schedule throws', async () => {
+ await expect(db.moveSchedule('missing', null)).rejects.toThrow(
+ 'Schedule not found: missing',
+ );
+ });
+
test('transactions get child transactions in the right order', async () => {
// Transactions on the same day should sort by sort order descending
await insertTransactions([
diff --git a/packages/loot-core/src/server/db/index.ts b/packages/loot-core/src/server/db/index.ts
index 60caaf9dbb..36da347334 100644
--- a/packages/loot-core/src/server/db/index.ts
+++ b/packages/loot-core/src/server/db/index.ts
@@ -896,6 +896,43 @@ export async function moveTransaction(
});
}
+/**
+ * Move a schedule to a new position among all non-tombstoned schedules.
+ * Uses the same midpoint/shove algorithm as transaction reordering.
+ *
+ * @param id - The ID of the schedule to move
+ * @param targetId - The ID of the schedule to place AFTER, or null to place at top
+ */
+export async function moveSchedule(id: string, targetId: string | null) {
+ await batchMessages(async () => {
+ const schedule = await first<{ id: string }>(
+ 'SELECT id FROM schedules WHERE id = ? AND tombstone = 0',
+ [id],
+ );
+ if (!schedule) {
+ throw new Error(`Schedule not found: ${id}`);
+ }
+
+ const schedules = await all<{ id: string; sort_order: number }>(
+ `SELECT id, sort_order FROM schedules
+ WHERE tombstone = 0
+ ORDER BY sort_order DESC, id`,
+ );
+
+ const { sort_order: newSortOrder, updates } = shoveSortOrdersDescending(
+ schedules,
+ targetId,
+ id,
+ );
+
+ for (const info of updates) {
+ await update('schedules', info);
+ }
+
+ await update('schedules', { id, sort_order: newSortOrder });
+ });
+}
+
/**
* Update sort_order of child/subtransactions to maintain relative ordering.
* Children are distributed evenly between the parent's sort_order and the
diff --git a/packages/loot-core/src/server/db/types/index.ts b/packages/loot-core/src/server/db/types/index.ts
index 6c5df63765..0dccc5f77f 100644
--- a/packages/loot-core/src/server/db/types/index.ts
+++ b/packages/loot-core/src/server/db/types/index.ts
@@ -140,6 +140,7 @@ export type DbSchedule = {
posts_transaction: 1 | 0;
custom_upcoming_length: string | null;
tombstone: 1 | 0;
+ sort_order: number;
};
// type DbScheduleJsonPath = {
diff --git a/packages/loot-core/src/server/schedules/app.ts b/packages/loot-core/src/server/schedules/app.ts
index 05a6645d90..f7e352eacf 100644
--- a/packages/loot-core/src/server/schedules/app.ts
+++ b/packages/loot-core/src/server/schedules/app.ts
@@ -307,6 +307,17 @@ function normalizeScheduleName(name) {
return trimmedName || null;
}
+async function moveSchedule({
+ id,
+ targetId,
+}: {
+ id: string;
+ targetId: string | null;
+}) {
+ await db.moveSchedule(id, targetId);
+ return {};
+}
+
export async function createSchedule({
schedule = null,
conditions = [],
@@ -793,6 +804,7 @@ export type SchedulesHandlers = {
'schedule/create': typeof createSchedule;
'schedule/update': typeof updateSchedule;
'schedule/delete': typeof deleteSchedule;
+ 'schedule/move': typeof moveSchedule;
'schedule/skip-next-date': typeof skipNextDate;
'schedule/post-transaction': typeof postTransactionForSchedule;
'schedule/force-run-service': typeof advanceSchedulesService;
@@ -806,6 +818,7 @@ export const app = createApp<SchedulesHandlers>();
app.method('schedule/create', mutator(undoable(createSchedule)));
app.method('schedule/update', mutator(undoable(updateSchedule)));
app.method('schedule/delete', mutator(undoable(deleteSchedule)));
+app.method('schedule/move', mutator(undoable(moveSchedule)));
app.method('schedule/skip-next-date', mutator(undoable(skipNextDate)));
app.method(
'schedule/post-transaction',
diff --git a/packages/loot-core/src/types/models/schedule.ts b/packages/loot-core/src/types/models/schedule.ts
index 389826b644..66e90ff606 100644
--- a/packages/loot-core/src/types/models/schedule.ts
+++ b/packages/loot-core/src/types/models/schedule.ts
@@ -28,6 +28,7 @@ export type ScheduleEntity = {
posts_transaction: boolean;
custom_upcoming_length?: string | null;
tombstone: boolean;
+ sort_order?: number;
// These are special fields that are actually pulled from the
// underlying rule
diff --git a/upcoming-release-notes/schedule-preview-drag-drop.md b/upcoming-release-notes/schedule-preview-drag-drop.md
new file mode 100644
index 0000000000..ca66380496
--- /dev/null
+++ b/upcoming-release-notes/schedule-preview-drag-drop.md
@@ -0,0 +1,6 @@
+---
+category: Enhancements
+authors: [StephenBrown2]
+---
+
+Drag-and-drop reordering for upcoming scheduled transactions.