Skip to content

Commit

Permalink
Rename external -> bankSync and a bit of cleanup
Browse files Browse the repository at this point in the history
  • Loading branch information
MatissJanis committed Apr 3, 2024
1 parent df35270 commit c8a741a
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 124 deletions.
94 changes: 25 additions & 69 deletions packages/loot-core/src/server/accounts/sync.ts
Original file line number Diff line number Diff line change
Expand Up @@ -328,7 +328,7 @@ async function normalizeTransactions(
return { normalized, payeesToCreate };
}

async function normalizeExternalTransactions(transactions, acctId) {
async function normalizeBankSyncTransactions(transactions, acctId) {
const payeesToCreate = new Map();

const normalized = [];
Expand Down Expand Up @@ -440,16 +440,16 @@ async function createNewPayees(payeesToCreate, addsAndUpdates) {
export async function reconcileTransactions(
acctId,
transactions,
isExternalAccount = false,
isBankSyncAccount = false,
) {
console.log('Performing transaction reconciliation');

const hasMatched = new Set();
const updated = [];
const added = [];

const transactionNormalization = isExternalAccount
? normalizeExternalTransactions
const transactionNormalization = isBankSyncAccount
? normalizeBankSyncTransactions
: normalizeTransactions;

const { normalized, payeesToCreate } = await transactionNormalization(
Expand Down Expand Up @@ -583,7 +583,7 @@ export async function reconcileTransactions(

// Update the transaction
const updates = {
...(isExternalAccount ? {} : { date: trans.date }),
...(isBankSyncAccount ? {} : { date: trans.date }),
imported_id: trans.imported_id || null,
payee: existing.payee || trans.payee || null,
category: existing.category || trans.category || null,
Expand Down Expand Up @@ -712,9 +712,6 @@ export async function syncAccount(
);

const acctRow = await db.select('accounts', id);
const isExternalAccount =
acctRow.account_sync_source === 'simpleFin' ||
acctRow.account_sync_source === 'goCardless';

if (latestTransaction) {
const startingTransaction = await db.first(
Expand Down Expand Up @@ -786,76 +783,39 @@ export async function syncAccount(
}));

return runMutator(async () => {
const result = await reconcileTransactions(
id,
transactions,
isExternalAccount,
);
const result = await reconcileTransactions(id, transactions, true);
await updateAccountBalance(id, accountBalance);
return result;
});
} else {
let balanceToUse: number;
let transactions;

if (isExternalAccount) {
let download;

// Otherwise, download transaction for the past 90 days
const startingDay = monthUtils.subDays(monthUtils.currentDay(), 90);
let download;

if (acctRow.account_sync_source === 'simpleFin') {
download = await downloadSimpleFinTransactions(acctId, startingDay);
} else if (acctRow.account_sync_source === 'goCardless') {
download = await downloadGoCardlessTransactions(
userId,
userKey,
acctId,
bankId,
startingDay,
);
}
// Otherwise, download transaction for the past 90 days
const startingDay = monthUtils.subDays(monthUtils.currentDay(), 90);

transactions = download.transactions;
balanceToUse = download.startingBalance;

if (acctRow.account_sync_source === 'simpleFin') {
const currentBalance = download.startingBalance;
const previousBalance = transactions.reduce((total, trans) => {
return (
total - parseInt(trans.transactionAmount.amount.replace('.', ''))
);
}, currentBalance);
balanceToUse = previousBalance;
}
} else {
// Otherwise, download transaction for the last few days if it's an
// on-budget account, or for the past 30 days if off-budget
const startingDay = monthUtils.subDays(
monthUtils.currentDay(),
acctRow.offbudget === 0 ? 1 : 30,
);

const download = await downloadTransactions(
if (acctRow.account_sync_source === 'simpleFin') {
download = await downloadSimpleFinTransactions(acctId, startingDay);
} else if (acctRow.account_sync_source === 'goCardless') {
download = await downloadGoCardlessTransactions(
userId,
userKey,
acctId,
bankId,
dateFns.format(dateFns.parseISO(startingDay), 'yyyy-MM-dd'),
startingDay,
);
}

transactions = download.transactions;

// We need to add a transaction that represents the starting
// balance for everything to balance out. In order to get balance
// before the first imported transaction, we need to get the
// current balance from the accounts table and subtract all the
// imported transactions.
const currentBalance = acctRow.balance_current;
const transactions = download.transactions;
let balanceToUse = download.startingBalance;

balanceToUse = transactions.reduce((total, trans) => {
return total - trans.amount;
if (acctRow.account_sync_source === 'simpleFin') {
const currentBalance = download.startingBalance;
const previousBalance = transactions.reduce((total, trans) => {
return (
total - parseInt(trans.transactionAmount.amount.replace('.', ''))
);
}, currentBalance);
balanceToUse = previousBalance;
}

const oldestTransaction = transactions[transactions.length - 1];
Expand All @@ -878,11 +838,7 @@ export async function syncAccount(
starting_balance_flag: true,
});

const result = await reconcileTransactions(
id,
transactions,
isExternalAccount,
);
const result = await reconcileTransactions(id, transactions, true);
return {
...result,
added: [initialId, ...result.added],
Expand Down
48 changes: 0 additions & 48 deletions packages/loot-core/src/server/main.ts
Original file line number Diff line number Diff line change
Expand Up @@ -610,54 +610,6 @@ handlers['account-properties'] = async function ({ id }) {
return { balance: balance || 0, numTransactions: count };
};

handlers['accounts-link'] = async function ({
institution,
publicToken,
accountId,
upgradingId,
}) {
const bankId = await link.handoffPublicToken(institution, publicToken);

const [[, userId], [, userKey]] = await asyncStorage.multiGet([
'user-id',
'user-key',
]);

// Get all the available accounts and find the selected one
const accounts = await bankSync.getGoCardlessAccounts(
userId,
userKey,
bankId,
);
const account = accounts.find(acct => acct.account_id === accountId);

await db.update('accounts', {
id: upgradingId,
account_id: account.account_id,
official_name: account.official_name,
balance_current: amountToInteger(account.balances.current),
balance_available: amountToInteger(account.balances.available),
balance_limit: amountToInteger(account.balances.limit),
mask: account.mask,
bank: bankId,
});

await bankSync.syncAccount(
userId,
userKey,
upgradingId,
account.account_id,
bankId,
);

connection.send('sync-event', {
type: 'success',
tables: ['transactions'],
});

return 'ok';
};

handlers['gocardless-accounts-link'] = async function ({
requisitionId,
account,
Expand Down
7 changes: 0 additions & 7 deletions packages/loot-core/src/types/server-handlers.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -149,13 +149,6 @@ export interface ServerHandlers {
id;
}) => Promise<{ balance: number; numTransactions: number }>;

'accounts-link': (arg: {
institution;
publicToken;
accountId;
upgradingId;
}) => Promise<'ok'>;

'gocardless-accounts-link': (arg: {
requisitionId;
account;
Expand Down

0 comments on commit c8a741a

Please sign in to comment.