Compare commits

...

7 Commits

Author SHA1 Message Date
efa9e785f2 🧹 Pino transports API and capture console.log
All checks were successful
Deploy application / deploy (push) Successful in 26s
2025-02-06 19:37:11 +01:00
71e70a2713 🧹 Delete token from db if expired 2025-02-06 19:13:23 +01:00
4f05382fc4 🚀 Daily is now Bank agnostic
- Separated createDir into a new file fs.ts
- Moved mapTransactions into Bank interface
- Take interval as input into importTransactions
2025-02-06 18:56:51 +01:00
066331cca8 🔪🐛 Fix corepack bug, removed unused envs, npm in docker
All checks were successful
Deploy application / deploy (push) Successful in 28s
- Replaced pnpm to npm in docker container because of a bug infestation
- Remove only allow pnpm
- Added missing envs to docker compose
2025-02-05 20:27:08 +01:00
75ad4946d2 🎉 Allow syncing multiple accounts at once
All checks were successful
Deploy application / deploy (push) Successful in 3s
- By defining multiple account keys in the .env, will fetch from all and upload to correct account
- If transaction id is 0, will not be marked as cleared
- Added accountKey to Transaction interface
2025-02-02 12:37:43 +01:00
14257fa058 ❄ Nix shell using flake 2025-02-02 12:34:09 +01:00
9b0391be7c Graceful shutdown on exceptions 2025-02-02 11:22:29 +01:00
17 changed files with 247 additions and 145 deletions

View File

@ -9,8 +9,6 @@ ACTUAL_DATA_DIR=.cache
BANK_INITIAL_REFRESH_TOKEN=initial-valid-refresh-token BANK_INITIAL_REFRESH_TOKEN=initial-valid-refresh-token
BANK_OAUTH_CLIENT_ID=your-client-id BANK_OAUTH_CLIENT_ID=your-client-id
BANK_OAUTH_CLIENT_SECRET=your-client-secret BANK_OAUTH_CLIENT_SECRET=your-client-secret
BANK_OAUTH_STATE=your-state
BANK_OAUTH_REDIRECT_URI=http://your-redirect-uri.com
BANK_ACCOUNT_IDS=your-account-id1,your-account-id2 BANK_ACCOUNT_IDS=your-account-id1,your-account-id2
# Configuration # Configuration
LOG_LEVEL=info# trace | error | warn | info | debug | trace LOG_LEVEL=info# trace | error | warn | info | debug | trace

View File

@ -15,13 +15,11 @@ jobs:
ACTUAL_SERVER_URL: ${{ secrets.ACTUAL_SERVER_URL }} ACTUAL_SERVER_URL: ${{ secrets.ACTUAL_SERVER_URL }}
ACTUAL_PASSWORD: ${{ secrets.ACTUAL_PASSWORD }} ACTUAL_PASSWORD: ${{ secrets.ACTUAL_PASSWORD }}
ACTUAL_ACCOUNT_IDS: ${{ secrets.ACTUAL_ACCOUNT_IDS }} ACTUAL_ACCOUNT_IDS: ${{ secrets.ACTUAL_ACCOUNT_IDS }}
ACTUAL_DATA_DIR: ${{ var.ACTUAL_DATA_DIR }} ACTUAL_DATA_DIR: ${{ vars.ACTUAL_DATA_DIR }}
# Bank # Bank
BANK_INITIAL_REFRESH_TOKEN: ${{ secrets.BANK_INITIAL_REFRESH_TOKEN }} BANK_INITIAL_REFRESH_TOKEN: ${{ secrets.BANK_INITIAL_REFRESH_TOKEN }}
BANK_OAUTH_CLIENT_ID: ${{ secrets.BANK_OAUTH_CLIENT_ID }} BANK_OAUTH_CLIENT_ID: ${{ secrets.BANK_OAUTH_CLIENT_ID }}
BANK_OAUTH_CLIENT_SECRET: ${{ secrets.BANK_OAUTH_CLIENT_SECRET }} BANK_OAUTH_CLIENT_SECRET: ${{ secrets.BANK_OAUTH_CLIENT_SECRET }}
BANK_OAUTH_STATE: ${{ secrets.BANK_OAUTH_STATE }}
BANK_OAUTH_REDIRECT_URI: ${{ secrets.BANK_OAUTH_REDIRECT_URI }}
BANK_ACCOUNT_IDS: ${{ secrets.BANK_ACCOUNT_IDS }} BANK_ACCOUNT_IDS: ${{ secrets.BANK_ACCOUNT_IDS }}
# Configuration # Configuration
LOG_LEVEL: ${{ vars.LOG_LEVEL }} LOG_LEVEL: ${{ vars.LOG_LEVEL }}

View File

@ -3,9 +3,6 @@ LABEL authors="Martin Berg Alstad"
COPY . . COPY . .
ENV PNPM_HOME="/pnpm" RUN --mount=type=cache,id=npm,target=/store npm install --omit=dev --frozen-lockfile
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --frozen-lockfile
CMD ["pnpm", "start-prod"] ENTRYPOINT ["npm", "run", "start-prod"]

View File

@ -1,7 +1,7 @@
services: services:
server: server:
container_name: actual_sparebank1_cronjob container_name: actual_sparebank1_cronjob
restart: unless-stopped restart: no
build: build:
context: . context: .
environment: environment:
@ -14,13 +14,14 @@ services:
- BANK_INITIAL_REFRESH_TOKEN - BANK_INITIAL_REFRESH_TOKEN
- BANK_OAUTH_CLIENT_ID - BANK_OAUTH_CLIENT_ID
- BANK_OAUTH_CLIENT_SECRET - BANK_OAUTH_CLIENT_SECRET
- BANK_OAUTH_STATE
- BANK_OAUTH_REDIRECT_URI
- BANK_ACCOUNT_IDS - BANK_ACCOUNT_IDS
- LOG_LEVEL - LOG_LEVEL
- DB_DIRECTORY # Required for Docker Compose - DB_DIRECTORY # Required for Docker Compose
- DB_FILENAME - DB_FILENAME
- TRANSACTION_RELATIVE_FROM_DATE
- TRANSACTION_RELATIVE_TO_DATE
volumes: volumes:
# TODO CACHE directory in volume?
- data:/${DB_DIRECTORY} - data:/${DB_DIRECTORY}
volumes: volumes:

27
flake.lock generated Normal file
View File

@ -0,0 +1,27 @@
{
"nodes": {
"nixpkgs": {
"locked": {
"lastModified": 1738277201,
"narHash": "sha256-6L+WXKCw5mqnUIExvqkD99pJQ41xgyCk6z/H9snClwk=",
"owner": "NixOS",
"repo": "nixpkgs",
"rev": "666e1b3f09c267afd66addebe80fb05a5ef2b554",
"type": "github"
},
"original": {
"owner": "NixOS",
"ref": "nixos-24.11",
"repo": "nixpkgs",
"type": "github"
}
},
"root": {
"inputs": {
"nixpkgs": "nixpkgs"
}
}
},
"root": "root",
"version": 7
}

28
flake.nix Normal file
View File

@ -0,0 +1,28 @@
{
inputs = {
nixpkgs.url = "github:NixOS/nixpkgs/nixos-24.11";
};
outputs = inputs@{ nixpkgs, ... }:
let
system = "x86_64-linux";
in
{
devShells.${system}.default =
let
pkgs = import nixpkgs {
inherit system;
};
in
pkgs.mkShell {
packages = with pkgs; [
git
nodejs_22
pnpm
nodePackages.prettier
];
shellHook = "fish";
};
};
}

View File

@ -51,6 +51,8 @@ GET {{bankingBaseUrl}}/accounts
Authorization: Bearer {{ACCESS_TOKEN}} Authorization: Bearer {{ACCESS_TOKEN}}
### Fetch all transactions of specific days (inclusive) ### Fetch all transactions of specific days (inclusive)
GET {{bankingBaseUrl}}/transactions?accountKey={{brukskontoAccountKey}}&fromDate=2025-01-20&toDate=2025-01-22 GET {{bankingBaseUrl}}/transactions?accountKey={{accountKey1}}&accountKey={{accountKey2}}&
fromDate=2025-01-20&
toDate=2025-01-24
Authorization: Bearer {{ACCESS_TOKEN}} Authorization: Bearer {{ACCESS_TOKEN}}
Accept: application/vnd.sparebank1.v1+json; charset=utf-8 Accept: application/vnd.sparebank1.v1+json; charset=utf-8

View File

@ -4,7 +4,6 @@
"description": "", "description": "",
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"preinstall": "npx only-allow pnpm",
"start": "dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | pino-pretty", "start": "dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | pino-pretty",
"start-prod": "node --import=tsx ./src/main.ts", "start-prod": "node --import=tsx ./src/main.ts",
"run-once": "ONCE=true dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | pino-pretty", "run-once": "ONCE=true dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | pino-pretty",

View File

@ -12,13 +12,14 @@ import logger from "@/logger.ts"
export interface Actual { export interface Actual {
importTransactions: ( importTransactions: (
accountId: UUID, accountId: UUID,
transactions: ReadonlyArray<ActualTransaction>, transactions: Iterable<ActualTransaction>,
) => Promise<ImportTransactionsResponse> ) => Promise<ImportTransactionsResponse>
shutdown: () => Promise<void> shutdown: () => Promise<void>
} }
export interface ActualTransaction extends TransactionEntity { export interface ActualTransaction extends TransactionEntity {
account: UUID
payee_name?: string payee_name?: string
} }
@ -51,7 +52,7 @@ export class ActualImpl implements Actual {
async importTransactions( async importTransactions(
accountId: UUID, accountId: UUID,
transactions: ReadonlyArray<ActualTransaction>, transactions: Iterable<ActualTransaction>,
): Promise<ImportTransactionsResponse> { ): Promise<ImportTransactionsResponse> {
return actual.importTransactions(accountId, transactions) return actual.importTransactions(accountId, transactions)
} }

View File

@ -50,7 +50,7 @@ function insertRefreshToken(
db: Database.Database, db: Database.Database,
refreshToken: string, refreshToken: string,
expiresIn: number, expiresIn: number,
) { ): void {
insert(db, "refresh-token", refreshToken, expiresIn) insert(db, "refresh-token", refreshToken, expiresIn)
} }
@ -59,7 +59,7 @@ function insert(
key: TokenKey, key: TokenKey,
token: string, token: string,
expiresIn: number, expiresIn: number,
) { ): void {
db.prepare("INSERT OR REPLACE INTO tokens VALUES (?, ?, ?)").run( db.prepare("INSERT OR REPLACE INTO tokens VALUES (?, ?, ?)").run(
key, key,
token, token,
@ -82,3 +82,10 @@ export function fetchToken(
} }
) )
} }
export function clearTokens(db: Database.Database): void {
db.prepare("DELETE FROM tokens WHERE key in ( ?, ? )").run([
"access-token",
"refresh-token",
] as TokenKey[])
}

View File

@ -1,17 +1,16 @@
import { import { BANK_INITIAL_REFRESH_TOKEN } from "@/../config.ts"
BANK_INITIAL_REFRESH_TOKEN,
TRANSACTION_RELATIVE_FROM_DATE,
TRANSACTION_RELATIVE_TO_DATE,
} from "@/../config.ts"
import logger from "@/logger.ts" import logger from "@/logger.ts"
import dayjs from "dayjs" import dayjs, { Dayjs } from "dayjs"
import { Database } from "better-sqlite3" import { Database } from "better-sqlite3"
import { import {
clearTokens,
fetchToken, fetchToken,
insertTokens, insertTokens,
type TokenResponse, type TokenResponse,
} from "@/bank/db/queries.ts" } from "@/bank/db/queries.ts"
import * as Api from "./sparebank1Api.ts" import * as Api from "./sparebank1Api.ts"
import { ActualTransaction } from "@/actual.ts"
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
export interface OAuthTokenResponse { export interface OAuthTokenResponse {
access_token: string access_token: string
@ -27,8 +26,12 @@ export type BookingStatus = "PENDING" | "BOOKED"
export interface Transaction { export interface Transaction {
id: string id: string
nonUniqueId: string nonUniqueId: string
date: number // Unix time // The Id of the account
amount: number // Amount in NOK accountKey: string
// Unix time
date: number
// Amount in NOK
amount: number
cleanedDescription: string cleanedDescription: string
remoteAccountName: string remoteAccountName: string
bookingStatus: BookingStatus bookingStatus: BookingStatus
@ -41,9 +44,15 @@ export interface TransactionResponse {
} }
export interface Bank { export interface Bank {
transactionsPastDay: ( fetchTransactions: (
interval: Interval,
...accountKeys: ReadonlyArray<string> ...accountKeys: ReadonlyArray<string>
) => Promise<TransactionResponse> ) => Promise<ReadonlyArray<ActualTransaction>>
}
export interface Interval {
fromDate: Dayjs
toDate: Dayjs
} }
export class Sparebank1Impl implements Bank { export class Sparebank1Impl implements Bank {
@ -53,6 +62,19 @@ export class Sparebank1Impl implements Bank {
this.db = db this.db = db
} }
async fetchTransactions(
interval: Interval,
...accountKeys: ReadonlyArray<string>
): Promise<ReadonlyArray<ActualTransaction>> {
const response = await Api.transactions(
await this.getAccessToken(),
accountKeys,
interval,
)
const sparebankTransactions = response.transactions
return sparebankTransactions.map(bankTransactionIntoActualTransaction)
}
private async getAccessToken(): Promise<string> { private async getAccessToken(): Promise<string> {
const accessToken = fetchToken(this.db, "access-token") const accessToken = fetchToken(this.db, "access-token")
@ -76,34 +98,21 @@ export class Sparebank1Impl implements Bank {
} else if (this.isValidToken(tokenResponse)) { } else if (this.isValidToken(tokenResponse)) {
return tokenResponse.token return tokenResponse.token
} }
// TODO clear database, if refresh token is invalid, will cause Exceptions on each call logger.warn("Refresh token expired, deleting tokens from database")
clearTokens(this.db)
throw new Error("Refresh token is expired. Create a new one") throw new Error("Refresh token is expired. Create a new one")
} }
async fetchNewTokens(): Promise<OAuthTokenResponse> { private async fetchNewTokens(): Promise<OAuthTokenResponse> {
const refreshToken = await this.getRefreshToken() const refreshToken = await this.getRefreshToken()
const result = await Api.refreshToken(refreshToken) const result = await Api.refreshToken(refreshToken)
if (result.status === "failure") { if (result.status === "failure") {
throw logger.error({ throw new Error(`Failed to fetch refresh token: '${result.data}'`)
err: new Error(`Failed to fetch refresh token: '${result.data}'`),
})
} }
const oAuthToken = result.data const oAuthToken = result.data
insertTokens(this.db, oAuthToken) insertTokens(this.db, oAuthToken)
return oAuthToken return oAuthToken
} }
async transactionsPastDay(
...accountKeys: ReadonlyArray<string>
): Promise<TransactionResponse> {
const today = dayjs()
const fromDate = today.subtract(TRANSACTION_RELATIVE_FROM_DATE, "days")
const toDate = today.subtract(TRANSACTION_RELATIVE_TO_DATE, "days")
return await Api.transactions(await this.getAccessToken(), accountKeys, {
fromDate,
toDate,
})
}
} }

View File

@ -1,11 +1,12 @@
import { BANK_OAUTH_CLIENT_ID, BANK_OAUTH_CLIENT_SECRET } from "../../config.ts" import { BANK_OAUTH_CLIENT_ID, BANK_OAUTH_CLIENT_SECRET } from "@/../config.ts"
import type { import type {
Interval,
OAuthTokenResponse, OAuthTokenResponse,
TransactionResponse, TransactionResponse,
} from "@/bank/sparebank1.ts" } from "@/bank/sparebank1.ts"
import logger from "@/logger.ts" import logger from "@/logger.ts"
import { type Dayjs } from "dayjs"
import { toISODateString } from "@/date.ts" import { toISODateString } from "@/date.ts"
import * as querystring from "node:querystring"
const baseUrl = "https://api.sparebank1.no" const baseUrl = "https://api.sparebank1.no"
@ -13,32 +14,23 @@ type Success<T> = { status: "success"; data: T }
type Failure<T> = { status: "failure"; data: T } type Failure<T> = { status: "failure"; data: T }
type Result<OK, Err> = Success<OK> | Failure<Err> type Result<OK, Err> = Success<OK> | Failure<Err>
function success<T>(data: T): Success<T> { const success = <T>(data: T): Success<T> => ({ status: "success", data: data })
return { status: "success", data: data } const failure = <T>(data: T): Failure<T> => ({ status: "failure", data: data })
}
function failure<T>(data: T): Failure<T> {
return { status: "failure", data: data }
}
export async function transactions( export async function transactions(
accessToken: string, accessToken: string,
accountKeys: string | ReadonlyArray<string>, accountKeys: string | ReadonlyArray<string>,
timePeriod?: { interval?: Interval,
fromDate: Dayjs
toDate: Dayjs
},
): Promise<TransactionResponse> { ): Promise<TransactionResponse> {
const queries = new URLSearchParams({ const queryString = querystring.stringify({
// TODO allow multiple accountKeys accountKey: accountKeys,
accountKey: typeof accountKeys === "string" ? accountKeys : accountKeys[0], ...(interval && {
...(timePeriod && { fromDate: toISODateString(interval.fromDate),
fromDate: toISODateString(timePeriod.fromDate), toDate: toISODateString(interval.toDate),
toDate: toISODateString(timePeriod.toDate),
}), }),
}) })
const url = `${baseUrl}/personal/banking/transactions?${queries}` const url = `${baseUrl}/personal/banking/transactions?${queryString}`
logger.debug(`Sending GET request to '${url}'`) logger.debug(`Sending GET request to '${url}'`)
const response = await fetch(url, { const response = await fetch(url, {
headers: { headers: {
@ -58,7 +50,7 @@ export async function transactions(
export async function refreshToken( export async function refreshToken(
refreshToken: string, refreshToken: string,
): Promise<Result<OAuthTokenResponse, string>> { ): Promise<Result<OAuthTokenResponse, string>> {
const queries = new URLSearchParams({ const queries = querystring.stringify({
client_id: BANK_OAUTH_CLIENT_ID, client_id: BANK_OAUTH_CLIENT_ID,
client_secret: BANK_OAUTH_CLIENT_SECRET, client_secret: BANK_OAUTH_CLIENT_SECRET,
refresh_token: refreshToken, refresh_token: refreshToken,

13
src/fs.ts Normal file
View File

@ -0,0 +1,13 @@
import * as fs from "node:fs"
import logger from "./logger"
export function createDirsIfMissing(...directories: string[]): void {
directories.forEach(createDirIfMissing)
}
export function createDirIfMissing(directory: string): void {
if (!fs.existsSync(directory)) {
logger.info(`Missing '${directory}', creating...`)
fs.mkdirSync(directory, { recursive: true })
}
}

View File

@ -4,6 +4,14 @@ import { LOG_LEVEL } from "../config.ts"
/** /**
* / Returns a logging instance with the default log-level "info" * / Returns a logging instance with the default log-level "info"
*/ */
export default pino({ const logger = pino(
pino.destination({
level: LOG_LEVEL, level: LOG_LEVEL,
}) }),
)
console.log = function (...args): void {
logger.info(args, args?.[0])
}
export default logger

View File

@ -1,73 +1,67 @@
import { type Actual, ActualImpl } from "@/actual.ts" import { type Actual, ActualImpl } from "@/actual.ts"
import { cronJobDaily } from "@/cron.ts" import { cronJobDaily } from "@/cron.ts"
import { type Bank, type Interval, Sparebank1Impl } from "@/bank/sparebank1.ts"
import { import {
type Bank,
Sparebank1Impl,
type Transaction,
} from "@/bank/sparebank1.ts"
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
import {
ACTUAL_ACCOUNT_IDS,
ACTUAL_DATA_DIR, ACTUAL_DATA_DIR,
BANK_ACCOUNT_IDS, BANK_ACCOUNT_IDS,
DB_DIRECTORY, DB_DIRECTORY,
DB_FILENAME, DB_FILENAME,
TRANSACTION_RELATIVE_FROM_DATE,
TRANSACTION_RELATIVE_TO_DATE,
} from "../config.ts" } from "../config.ts"
import logger from "@/logger.ts" import logger from "@/logger.ts"
import type { UUID } from "node:crypto" import type { UUID } from "node:crypto"
import { createDb } from "@/bank/db/queries.ts" import { createDb } from "@/bank/db/queries.ts"
import * as fs from "node:fs"
import { CronJob } from "cron" import { CronJob } from "cron"
import { createDirsIfMissing } from "@/fs.ts"
import dayjs from "dayjs"
// TODO Transports api for pino https://github.com/pinojs/pino/blob/HEAD/docs/transports.md
// TODO move tsx to devDependency. Requires ts support for Node with support for @ alias // TODO move tsx to devDependency. Requires ts support for Node with support for @ alias
// TODO global exception handler, log and graceful shutdown
// TODO verbatimSyntax in tsconfig, conflicts with jest // TODO verbatimSyntax in tsconfig, conflicts with jest
// TODO multi module project. Main | DAL | Sparebank1 impl // TODO multi module project. Main | DAL | Sparebank1 impl
// TODO store last fetched date in db, and refetch from that date, if app has been offline for some time // TODO store last fetched date in db, and refetch from that date, if app has been offline for some time
// TODO do not fetch if saturday or sunday
export async function daily(actual: Actual, bank: Bank): Promise<void> { export async function daily(actual: Actual, bank: Bank): Promise<void> {
// Fetch transactions from the bank // Fetch transactions from the bank
const transactions = await fetchTransactionsFromPastDay(bank) const actualTransactions = await bank.fetchTransactions(
logger.info(`Fetched ${transactions.length} transactions`) relativeInterval(),
...BANK_ACCOUNT_IDS,
// TODO multiple accounts
const accountId = ACTUAL_ACCOUNT_IDS[0] as UUID
const actualTransactions = transactions.map((transaction) =>
// TODO move to Bank interface?
bankTransactionIntoActualTransaction(transaction, accountId),
) )
logger.info(`Fetched ${actualTransactions.length} transactions`)
// TODO Import transactions into Actual const transactionsByAccount = Object.groupBy(
// If multiple accounts, loop over them
// Get account ID from mapper
const response = await actual.importTransactions(
accountId,
actualTransactions, actualTransactions,
(transaction) => transaction.account,
)
const responses = await Promise.all(
Object.entries(transactionsByAccount).map(([accountId, transactions]) =>
actual.importTransactions(accountId as UUID, transactions || []),
),
)
logger.debug(
responses.map((response) => ({
added: response.added,
updated: response.updated,
})),
"Finished importing transactions",
) )
logger.info(`ImportTransactionsResponse=${JSON.stringify(response)}`)
} }
async function fetchTransactionsFromPastDay( function relativeInterval(): Interval {
bank: Bank, const today = dayjs()
): Promise<ReadonlyArray<Transaction>> { return {
const response = await bank.transactionsPastDay(...BANK_ACCOUNT_IDS) fromDate: today.subtract(TRANSACTION_RELATIVE_FROM_DATE, "days"),
return response.transactions toDate: today.subtract(TRANSACTION_RELATIVE_TO_DATE, "days"),
}
function createDirIfMissing(directory: string): void {
if (!fs.existsSync(directory)) {
logger.info(`Missing '${directory}', creating...`)
fs.mkdirSync(directory, { recursive: true })
} }
} }
async function main(): Promise<void> { async function main(): Promise<void> {
logger.info("Starting application") logger.info("Starting application")
createDirIfMissing(ACTUAL_DATA_DIR) createDirsIfMissing(ACTUAL_DATA_DIR, DB_DIRECTORY)
createDirIfMissing(DB_DIRECTORY)
const actual = await ActualImpl.init() const actual = await ActualImpl.init()
const databaseFilePath = `${DB_DIRECTORY}/${DB_FILENAME}.sqlite` const databaseFilePath = `${DB_DIRECTORY}/${DB_FILENAME}.sqlite`
@ -82,14 +76,21 @@ async function main(): Promise<void> {
let cronJob: CronJob | undefined let cronJob: CronJob | undefined
if (process.env.ONCE) { if (process.env.ONCE) {
await daily(actual, bank) try {
return await daily(actual, bank)
} finally {
await shutdown() await shutdown()
return }
} }
logger.info("Waiting for CRON job to start") logger.info("Waiting for CRON job to start")
// TODO init and shutdown resources when job runs? // TODO init and shutdown resources when job runs?
try {
cronJob = cronJobDaily(async () => await daily(actual, bank)) cronJob = cronJobDaily(async () => await daily(actual, bank))
} catch (exception) {
logger.error(exception, "Caught exception at daily job, shutting down!")
await shutdown()
}
async function shutdown(): Promise<void> { async function shutdown(): Promise<void> {
logger.info("Shutting down, Bye!") logger.info("Shutting down, Bye!")

View File

@ -3,27 +3,44 @@ import type { UUID } from "node:crypto"
import dayjs from "dayjs" import dayjs from "dayjs"
import { toISODateString } from "@/date.ts" import { toISODateString } from "@/date.ts"
import { type ActualTransaction } from "@/actual.ts" import { type ActualTransaction } from "@/actual.ts"
import { ACTUAL_ACCOUNT_IDS, BANK_ACCOUNT_IDS } from "../config.ts"
import logger from "@/logger.ts"
export function bankTransactionIntoActualTransaction( export function bankTransactionIntoActualTransaction(
transaction: Transaction, transaction: Transaction,
accountId: UUID,
): ActualTransaction { ): ActualTransaction {
return { return {
id: transaction.id, id: transaction.id,
// Transactions with the same id will be ignored // Transactions with the same id will be ignored
imported_id: transaction.nonUniqueId, imported_id: transaction.nonUniqueId,
account: accountId, account: getActualAccountId(transaction),
// The value without decimals // The value without decimals
amount: transaction.amount * 100, amount: Math.floor(transaction.amount * 100),
date: toISODateString(dayjs(transaction.date)), date: toISODateString(dayjs(transaction.date)),
payee_name: transaction.cleanedDescription, payee_name: transaction.cleanedDescription,
// TODO if not cleared or nonUniqueId is 0, rerun later // TODO if not cleared or nonUniqueId is 0, rerun later
cleared: transaction.bookingStatus === "BOOKED", cleared: isCleared(transaction),
} }
} }
// TODO take the account from the bank and match it to the actual account export function isCleared(transaction: Transaction): boolean {
// Use ENV const id = Number(transaction.nonUniqueId)
export function bankAccountIntoActualAccount(account: string): string { return transaction.bookingStatus === "BOOKED" && !Number.isNaN(id) && id > 0
throw new Error("Not implemented") }
function getActualAccountId(transcation: Transaction): UUID {
for (
let i = 0;
i < Math.min(ACTUAL_ACCOUNT_IDS.length, BANK_ACCOUNT_IDS.length);
i++
) {
if (BANK_ACCOUNT_IDS[i] === transcation.accountKey) {
return ACTUAL_ACCOUNT_IDS[i] as UUID
}
}
const error = new Error(
"Failed to find ActualAccountId, length of BANK_ACCOUNT_IDS and ACTUAL_ACCOUNT_IDS must match",
)
logger.error(error)
throw error
} }

View File

@ -1,22 +1,26 @@
import type { import type {
Bank, Bank,
BookingStatus, BookingStatus,
TransactionResponse, Interval,
Transaction,
} from "@/bank/sparebank1.ts" } from "@/bank/sparebank1.ts"
import dayjs from "dayjs" import dayjs from "dayjs"
import { ActualTransaction } from "@/actual.ts"
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
export class BankStub implements Bank { export class BankStub implements Bank {
async transactionsPastDay( async fetchTransactions(
_interval: Interval,
_accountIds: ReadonlyArray<string> | string, _accountIds: ReadonlyArray<string> | string,
): Promise<TransactionResponse> { ): Promise<ReadonlyArray<ActualTransaction>> {
const someFields = { const someFields = {
date: dayjs("2019-08-20").unix(), date: dayjs("2019-08-20").unix(),
cleanedDescription: "Test transaction", cleanedDescription: "Test transaction",
remoteAccountName: "Test account", remoteAccountName: "Test account",
bookingStatus: "BOOKED" as BookingStatus, bookingStatus: "BOOKED" as BookingStatus,
accountKey: "1",
} }
return { const bankTransactions: ReadonlyArray<Transaction> = [
transactions: [
{ {
id: "1", id: "1",
nonUniqueId: "1", nonUniqueId: "1",
@ -35,7 +39,7 @@ export class BankStub implements Bank {
amount: -50, amount: -50,
...someFields, ...someFields,
}, },
], ]
} return bankTransactions.map(bankTransactionIntoActualTransaction)
} }
} }