Skip to content

A local-first personal finance app

15.0 KB
Raw Blame
import * as db from '#server/db';
// @ts-strict-ignore
import type { TransactionEntity } from '#types/models';

import { mergeTransactions } from './merge';

describe('Merging fails for invalid quantity', () => {
  beforeEach(global.emptyDatabase());
  afterEach(global.emptyDatabase());

  const tests: [TransactionEntity[], string][] = [
    [[{} as TransactionEntity], 'one transaction'],
    [[], 'no transactions'],
    [undefined as unknown as TransactionEntity[], 'undefined'],
    [[{}, {}, {}] as TransactionEntity[], 'three transactions'],
    [
      [{}, undefined] as TransactionEntity[],
      'two transactions but one is undefined',
    ],
  ];
  tests.forEach(([arr, message]) =>
    it(message, () => expect(() => mergeTransactions(arr)).rejects.toThrow()),
  );

  it("fails when amounts don't match", async () => {
    await prepareDatabase();
    const t1 = await db.insertTransaction({
      account: 'one',
      date: '2025-01-01',
      amount: 10,
    });
    const t2 = await db.insertTransaction({
      account: 'one',
      date: '2025-01-01',
      amount: 12,
    });
    await expect(() =>
      mergeTransactions([{ id: t1 }, { id: t2 }]),
    ).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({
      account: 'one',
      date: '2025-01-01',
      amount: 10,
    });
    await expect(() =>
      mergeTransactions([{ id: t1 }, { id: 'missing' }]),
    ).rejects.toThrow('One of the provided transactions does not exist');
  });
});

async function prepareDatabase() {
  await db.insertCategoryGroup({ id: 'group1', name: 'group1', is_income: 0 });
  await db.insertCategory({
    id: '1',
    name: 'cat1',
    cat_group: 'group1',
    is_income: 0,
  });
  await db.insertCategory({
    id: '2',
    name: 'cat2',
    cat_group: 'group1',
    is_income: 0,
  });
  await db.insertAccount({ id: 'one', name: 'one' });
  await db.insertAccount({ id: 'two', name: 'two' });
  await db.insertAccount({ id: 'three', name: 'three', offbudget: 1 });
  await db.insertPayee({ id: 'payee1', name: 'one' });
  await db.insertPayee({ id: 'payee2', name: 'two' });
  await db.insertPayee({ id: 'payee3', name: 'three' });
}

function getAllTransactions() {
  return db.all<db.DbViewTransaction & { payee_name: db.DbPayee['name'] }>(
    `SELECT t.*, p.name as payee_name
       FROM v_transactions t
       LEFT JOIN payees p ON p.id = t.payee
       ORDER BY date DESC, amount DESC, id
     `,
  );
}

describe('Merging success', () => {
  beforeEach(global.emptyDatabase());
  beforeEach(prepareDatabase);
  afterEach(global.emptyDatabase());
  const transaction1 = {
    account: 'one',
    date: '2025-01-01',
    payee: 'payee1',
    notes: 'notes1',
    category: '1',
    amount: 5,
    cleared: false,
    reconciled: false,
  } as TransactionEntity;

  const dbTransaction1 = {
    account: 'one',
    date: 20250101,
    payee: 'payee1',
    notes: 'notes1',
    category: '1',
    amount: 5,
    cleared: 1,
    reconciled: 1,
  } as db.DbViewTransaction;

  const transaction2 = {
    account: 'one',
    date: '2025-02-02',
    payee: 'payee2',
    notes: 'notes2',
    category: '2',
    amount: 5,
    cleared: true,
    reconciled: true,
  } as TransactionEntity;

  const dbTransaction2 = {
    account: 'one',
    date: 20250202,
    payee: 'payee2',
    notes: 'notes2',
    category: '2',
    amount: 5,
    cleared: 1,
    reconciled: 1,
  } as db.DbViewTransaction;

  it('two banksynced transactions keeps older transaction', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_id: 'imported_1',
    });
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_id: 'imported_2',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction1,
      imported_id: 'imported_1',
    });
  });

  it('first banksynced, second manual keeps banksynced values', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_id: 'imported_1',
    });
    const t2 = await db.insertTransaction(transaction2);

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction1,
      imported_id: 'imported_1',
    });
  });

  it('first file imported, second banksycned keeps banksynced values', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_payee: 'payee',
    });
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_id: 'imported_2',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t2);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction2,
      imported_id: 'imported_2',
    });
  });

  it('second file imported, first banksycned keeps banksynced values', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_id: 'imported_1',
    });
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_payee: 'payee',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction1,
      imported_id: 'imported_1',
    });
  });

  it('second file imported, first manual keeps file imported values', async () => {
    const t1 = await db.insertTransaction(transaction1);
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_payee: 'payee',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t2);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction2,
      imported_payee: 'payee',
    });
  });

  it('first file imported, second manual keeps file imported values', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_payee: 'payee',
    });
    const t2 = await db.insertTransaction(transaction2);

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction1,
      imported_payee: 'payee',
    });
  });

  it('second banksynced, first manual keeps banksynced values', async () => {
    const t1 = await db.insertTransaction(transaction1);
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_id: 'imported_2',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t2);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction2,
      imported_id: 'imported_2',
    });
  });

  it('missing values in keep are filled in with drop values', async () => {
    // only insert required fields, imported to be kept
    const t1 = await db.insertTransaction({
      account: 'one',
      amount: 5,
      date: '2025-01-01',
      imported_id: 'imported_1',
    });
    const t2 = await db.insertTransaction(transaction2);

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);
    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0]).toMatchObject({
      ...dbTransaction2,
      // values that should be kept from t1
      id: t1,
      account: 'one',
      amount: 5,
      date: 20250101,
      imported_id: 'imported_1',
    });
  });

  it('preserves schedule link from dropped transaction when kept transaction has none', async () => {
    const t1 = await db.insertTransaction({
      account: 'one',
      amount: 5,
      date: '2025-01-01',
      imported_id: 'imported_1',
    });
    const t2 = await db.insertTransaction({
      ...transaction2,
      schedule: 'schedule-1',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);
    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0].schedule).toBe('schedule-1');
  });

  it('preserves schedule link from kept transaction when both have schedules', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      imported_id: 'imported_1',
      schedule: 'schedule-keep',
    });
    const t2 = await db.insertTransaction({
      ...transaction2,
      schedule: 'schedule-drop',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);
    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0].schedule).toBe('schedule-keep');
  });

  it('preserves schedule link when merging manual scheduled with banksynced', async () => {
    // Manual transaction linked to a schedule
    const t1 = await db.insertTransaction({
      ...transaction1,
      schedule: 'schedule-1',
    });
    // Bank-synced transaction (kept due to imported_id priority)
    const t2 = await db.insertTransaction({
      ...transaction2,
      imported_id: 'imported_2',
    });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t2);
    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(1);
    expect(transactions[0].schedule).toBe('schedule-1');
  });

  it('preserves split categories when merging split transaction with uncategorized imported transaction', async () => {
    // Create a manual transaction with splits
    const manualParent = await db.insertTransaction({
      account: 'one',
      amount: 100,
      date: '2025-01-01',
      is_parent: true,
      category: null,
    });

    const _sub1 = await db.insertTransaction({
      account: 'one',
      amount: 60,
      date: '2025-01-01',
      category: '1',
      notes: 'Food',
      is_child: true,
      parent_id: manualParent,
    });

    const _sub2 = await db.insertTransaction({
      account: 'one',
      amount: 40,
      date: '2025-01-01',
      category: '2',
      notes: 'Transport',
      is_child: true,
      parent_id: manualParent,
    });

    // Create an uncategorized imported transaction
    const imported = await db.insertTransaction({
      account: 'one',
      amount: 100,
      date: '2025-01-02',
      imported_id: 'imported_1',
      category: null,
    });

    // Merge: imported transaction should be kept (because it has imported_id)
    const keptId = await mergeTransactions([
      { id: manualParent },
      { id: imported },
    ]);
    expect(keptId).toBe(imported);

    // Check that the kept transaction is now a parent
    const keptTransaction = await db.getTransaction(imported);
    expect(keptTransaction?.is_parent).toBe(true);
    expect(keptTransaction?.category).toBeNull();
    expect(keptTransaction?.imported_id).toBe('imported_1');

    // Check that subtransactions were transferred and still exist
    const allTransactions = await getAllTransactions();
    const childTransactions = allTransactions.filter(
      t => t.parent_id === imported,
    );
    expect(childTransactions.length).toBe(2);

    // Verify the subtransactions have the correct parent_id and preserved their categories
    const child1 = childTransactions.find(t => t.amount === 60);
    const child2 = childTransactions.find(t => t.amount === 40);

    expect(child1).toMatchObject({
      parent_id: imported,
      category: '1',
      notes: 'Food',
      is_child: 1, // From getAllTransactions (db.all), not converted
    });

    expect(child2).toMatchObject({
      parent_id: imported,
      category: '2',
      notes: 'Transport',
      is_child: 1, // From getAllTransactions (db.all), not converted
    });

    // Verify no orphaned subtransactions remain
    const orphanedChildren = allTransactions.filter(
      t => t.parent_id === manualParent,
    );
    expect(orphanedChildren.length).toBe(0);
  });

  it('transfer link is preserved on drop', async () => {
    const t1 = await db.insertTransaction({
      ...transaction1,
      category: 'category_id',
      imported_id: 'import_1',
      imported_payee: 'payee_import_2',
    });

    const t2 = await db.insertTransaction({
      ...transaction2,
    });
    const t2Transfer = await db.insertTransaction({
      ...transaction2,
      account: 'one',
      amount: -transaction2.amount,
      transfer_id: t2,
    });
    await db.updateTransaction({ id: t2, transfer_id: t2Transfer });

    expect(await mergeTransactions([{ id: t1 }, { id: t2 }])).toBe(t1);
    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(2);
    const t1R = transactions.find(tx => tx.id === t1);
    const t2TransferR = transactions.find(tx => tx.id === t2Transfer);
    expect(t1R).toBeTruthy();
    expect(t2TransferR).toBeTruthy();
    expect(t2TransferR?.transfer_id).toBe(t1);
    expect(t1R?.transfer_id).toBe(t2Transfer);
    expect(t1R?.imported_id).toBe('import_1');
    expect(t1R?.imported_payee).toBe('payee_import_2');
  });

  it('merging two transfers selects the best transaction in each account to preserve', async () => {
    // A -> B
    const a = await db.insertTransaction({
      ...transaction1,
      amount: -10,
      date: '2025-01-01', // A is earlier than C
    });
    const b = await db.insertTransaction({
      ...transaction2,
      amount: 10,
      date: '2025-01-05', // B is later than D
      transfer_id: a,
    });
    await db.updateTransaction({ id: a, transfer_id: b });

    // C -> D
    const c = await db.insertTransaction({
      ...transaction1,
      amount: -10,
      date: '2025-01-03', // C is later than A
    });
    const d = await db.insertTransaction({
      ...transaction2,
      amount: 10,
      date: '2025-01-02', // D is earlier than B
      transfer_id: c,
    });
    await db.updateTransaction({ id: c, transfer_id: d });

    // Merge A and C
    expect(await mergeTransactions([{ id: a }, { id: c }])).toBe(a);

    const transactions = await getAllTransactions();
    expect(transactions.length).toBe(2);

    expect(transactions[0].id).toBe(d); // 2025-01-02 is more recent than 2025-01-01
    expect(transactions[1].id).toBe(a);

    expect(transactions[0].transfer_id).toBe(a);
    expect(transactions[1].transfer_id).toBe(d);
  });
});