2024-11-17 22:27:29 +01:00
|
|
|
import { type Actual, ActualImpl } from "@/actual.ts"
|
|
|
|
import { cronJobDaily } from "@/cron.ts"
|
2024-12-01 19:35:45 +01:00
|
|
|
import { type Bank, Sparebank1Impl, type Transaction } from "@/sparebank1.ts"
|
2024-12-01 20:48:42 +01:00
|
|
|
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
|
2024-12-01 19:35:45 +01:00
|
|
|
import { ACTUAL_ACCOUNT_IDS, BANK_ACCOUNT_IDS } from "../config.ts"
|
|
|
|
import logger from "pino"
|
|
|
|
import type { UUID } from "node:crypto"
|
2024-11-15 22:55:53 +01:00
|
|
|
|
2024-12-01 19:35:45 +01:00
|
|
|
// TODO Transports api for pino https://github.com/pinojs/pino/blob/HEAD/docs/transports.md
|
2024-12-01 20:48:42 +01:00
|
|
|
// TODO create .cache if missing
|
2024-11-15 22:55:53 +01:00
|
|
|
|
2024-12-01 20:48:42 +01:00
|
|
|
export async function daily(actual: Actual, bank: Bank): Promise<void> {
|
2024-12-01 19:35:45 +01:00
|
|
|
// Fetch transactions from the bank
|
|
|
|
const transactions = await fetchTransactionsFromPastDay(bank)
|
|
|
|
logger().info(`Fetched ${transactions.length} transactions`)
|
2024-11-15 22:55:53 +01:00
|
|
|
|
2024-12-01 19:35:45 +01:00
|
|
|
// TODO multiple accounts
|
|
|
|
const accountId = ACTUAL_ACCOUNT_IDS[0] as UUID
|
|
|
|
const actualTransactions = transactions.map((transaction) =>
|
2024-12-01 20:48:42 +01:00
|
|
|
bankTransactionIntoActualTransaction(transaction, accountId),
|
2024-12-01 19:35:45 +01:00
|
|
|
)
|
|
|
|
|
|
|
|
// TODO Import transactions into Actual
|
|
|
|
// If multiple accounts, loop over them
|
|
|
|
// Get account ID from mapper
|
2024-12-01 20:48:42 +01:00
|
|
|
|
|
|
|
// TODO TypeError: Cannot read properties of undefined (reading 'timestamp')
|
2024-12-01 19:35:45 +01:00
|
|
|
await actual.importTransactions(accountId, actualTransactions)
|
|
|
|
}
|
|
|
|
|
|
|
|
async function fetchTransactionsFromPastDay(
|
|
|
|
bank: Bank,
|
|
|
|
): Promise<ReadonlyArray<Transaction>> {
|
|
|
|
// TODO refresh token
|
|
|
|
const { access_token } = await bank.refreshToken("my_refresh_token")
|
|
|
|
return bank.transactionsPastDay(BANK_ACCOUNT_IDS, access_token)
|
2024-11-17 22:27:29 +01:00
|
|
|
}
|
2024-11-15 22:55:53 +01:00
|
|
|
|
2024-11-17 22:27:29 +01:00
|
|
|
async function main(): Promise<void> {
|
2024-12-01 19:35:45 +01:00
|
|
|
logger().info("Starting application")
|
2024-11-17 22:27:29 +01:00
|
|
|
const actual = await ActualImpl.init()
|
2024-12-01 20:48:42 +01:00
|
|
|
logger().info("Initialized Actual Budget API")
|
|
|
|
|
2024-12-01 19:35:45 +01:00
|
|
|
cronJobDaily(async () => {
|
|
|
|
logger().info("Running daily job")
|
|
|
|
await daily(actual, new Sparebank1Impl())
|
|
|
|
logger().info("Finished daily job")
|
|
|
|
})
|
2024-12-01 20:48:42 +01:00
|
|
|
|
|
|
|
// logger().info("Shutting down")
|
2024-11-17 22:27:29 +01:00
|
|
|
// await actual.shutdown()
|
2024-11-15 22:55:53 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
void main()
|