A local-first personal finance app
[AI] Add mergeTransactions to the API (#8877)
Haim Gelfenbeyn041f9f3b6e9a
diff --git a/packages/api/methods.test.ts b/packages/api/methods.test.tsindex b747381c0c..6f99cd56c8 100644--- a/packages/api/methods.test.ts+++ b/packages/api/methods.test.ts@@ -954,6 +954,33 @@ describe('API CRUD operations', () => {expect(transactions).toHaveLength(1);});+ // apis: mergeTransactions+ test('Transactions: successfully merge two transactions', async () => {+ const accountId = await api.createAccount({ name: 'test-account' }, 0);++ await api.addTransactions(accountId, [+ { date: '2023-11-03', amount: 100, notes: 'notes' },+ { date: '2023-11-03', amount: 100, imported_id: '1' },+ ]);++ const before = await api.getTransactions(+ accountId,+ '2023-11-01',+ '2023-11-30',+ );+ expect(before).toHaveLength(2);++ const keptId = await api.mergeTransactions([before[0].id, before[1].id]);++ const after = await api.getTransactions(+ accountId,+ '2023-11-01',+ '2023-11-30',+ );+ expect(after).toHaveLength(1);+ expect(after[0]).toMatchObject({ id: keptId, notes: 'notes' });+ });+test('Transactions: import notes are preserved when importing', async () => {const accountId = await api.createAccount({ name: 'test-account' }, 0);diff --git a/packages/api/methods.ts b/packages/api/methods.tsindex df42679b48..f5bcf354be 100644--- a/packages/api/methods.ts+++ b/packages/api/methods.ts@@ -213,6 +213,12 @@ export function deleteTransaction(id: TransactionEntity['id']) {return send('api/transaction-delete', { id });}+export function mergeTransactions(+ ids: [TransactionEntity['id'], TransactionEntity['id']],+) {+ return send('api/transactions-merge', { ids });+}+export function getAccounts() {return send('api/accounts-get');}diff --git a/packages/docs/docs/api/reference.md b/packages/docs/docs/api/reference.mdindex c4a47167f4..a116a296b2 100644--- a/packages/docs/docs/api/reference.md+++ b/packages/docs/docs/api/reference.md@@ -20,7 +20,8 @@ import APIList from './APIList';"importTransactions","getTransactions","updateTransaction",-"deleteTransaction"+"deleteTransaction",+"mergeTransactions"]} /><APIList title="Accounts" sections={[@@ -314,6 +315,21 @@ Update fields of a transaction. `fields` can specify any field described in [`TrDelete a transaction.+#### `mergeTransactions`++<Method name="mergeTransactions" args={[{ name: 'ids', type: 'id[]' }]} returns="Promise<id>" />++Merge exactly two distinct transactions from the same account into one. Returns the id of the surviving transaction; the other one is deleted.++The order of the ids does not decide which transaction survives:++- an imported transaction is kept over a manually entered one+- otherwise, the transaction with the earlier date is kept++The surviving transaction keeps its own field values and fills in any empty ones from the deleted transaction. It is marked cleared if either transaction was.++The merge fails if you pass the same id twice, or if the two transactions are in different accounts, have different amounts, or are transfers to different accounts.+#### Examples```jsdiff --git a/packages/loot-core/src/server/api.ts b/packages/loot-core/src/server/api.tsindex 168099aa0e..dd819a00a3 100644--- a/packages/loot-core/src/server/api.ts+++ b/packages/loot-core/src/server/api.ts@@ -613,6 +613,11 @@ handlers['api/transaction-delete'] = withMutation(async function ({ id }) {return handlers['transactions-batch-update'](diff)['deleted'];});+handlers['api/transactions-merge'] = withMutation(async function ({ ids }) {+ checkFileOpen();+ return handlers['transactions-merge'](ids.map(id => ({ id })));+});+handlers['api/accounts-get'] = async function () {checkFileOpen();const accounts: AccountEntity[] = await handlers['accounts-get']();diff --git a/packages/loot-core/src/server/transactions/merge.test.ts b/packages/loot-core/src/server/transactions/merge.test.tsindex bf7587454b..28aa35e8a6 100644--- a/packages/loot-core/src/server/transactions/merge.test.ts+++ b/packages/loot-core/src/server/transactions/merge.test.ts@@ -39,6 +39,19 @@ describe('Merging fails for invalid quantity', () => {).rejects.toThrow('Cannot merge transactions with different amounts');});+ it('fails when the same transaction is passed twice', async () => {+ await prepareDatabase();+ const t1 = await db.insertTransaction({+ account: 'one',+ date: '2025-01-01',+ amount: 10,+ });+ await expect(() =>+ mergeTransactions([{ id: t1 }, { id: t1 }]),+ ).rejects.toThrow('Merging is only possible with 2 distinct transactions');+ expect(await db.getTransaction(t1)).toBeTruthy();+ });+it("fails when transaction id doesn't exist", async () => {await prepareDatabase();const t1 = await db.insertTransaction({diff --git a/packages/loot-core/src/server/transactions/merge.ts b/packages/loot-core/src/server/transactions/merge.tsindex 8a706e3bd7..e42c2e0d01 100644--- a/packages/loot-core/src/server/transactions/merge.ts+++ b/packages/loot-core/src/server/transactions/merge.ts@@ -15,9 +15,9 @@ export async function mergeTransactions(): Promise<TransactionEntity['id']> {// make sure all values have idsconst txIds = transactions?.map(x => x?.id).filter(Boolean) || [];- if (txIds.length !== 2) {+ if (txIds.length !== 2 || new Set(txIds).size !== 2) {throw new Error(- 'Merging is only possible with 2 transactions, but found ' ++ 'Merging is only possible with 2 distinct transactions, but found ' +JSON.stringify(transactions),);}diff --git a/packages/loot-core/src/types/api-handlers.ts b/packages/loot-core/src/types/api-handlers.tsindex 2b89b3e292..679a8c97b3 100644--- a/packages/loot-core/src/types/api-handlers.ts+++ b/packages/loot-core/src/types/api-handlers.ts@@ -134,6 +134,10 @@ export type ApiHandlers = {id: TransactionEntity['id'];}) => Promise<Awaited<ReturnType<typeof batchUpdateTransactions>>['deleted']>;+ 'api/transactions-merge': (arg: {+ ids: [TransactionEntity['id'], TransactionEntity['id']];+ }) => Promise<TransactionEntity['id']>;+'api/sync': () => Promise<void>;'api/bank-sync': (arg?: {diff --git a/upcoming-release-notes/api-merge-transactions.md b/upcoming-release-notes/api-merge-transactions.mdnew file mode 100644index 0000000000..ac0ebe8236--- /dev/null+++ b/upcoming-release-notes/api-merge-transactions.md@@ -0,0 +1,6 @@+---+category: Enhancements+authors: [haimgel]+---++Add `mergeTransactions` to the API so integrations can merge two duplicate transactions