Compare commits

...

42 Commits

Author SHA1 Message Date
2e68da2352 📦 Update dependencies
All checks were successful
Deploy application / deploy (push) Successful in 3s
2025-07-03 20:00:06 +02:00
f68afd0ff7 ⬆️ Updated dependencies
All checks were successful
Deploy application / deploy (push) Successful in 19s
2025-05-15 18:00:05 +02:00
7ea55567da ⬆️ Update actual api to 25.3, cron to 4
All checks were successful
Deploy application / deploy (push) Successful in 18s
2025-03-02 08:37:38 +01:00
080b65854d 🐛 Do not upload transactions that are not booked
All checks were successful
Deploy application / deploy (push) Successful in 8s
2025-02-16 18:22:10 +01:00
a0cefcdfa1 ️ Return early if no transactions were fetched 2025-02-16 18:07:48 +01:00
a2c6c55430 🐛 Fix relative dates are wrong
All checks were successful
Deploy application / deploy (push) Successful in 9s
2025-02-15 12:53:50 +01:00
0e83172558 🔪🐛 Fix docker volume in wrong directory
All checks were successful
Deploy application / deploy (push) Successful in 3s
2025-02-14 17:08:10 +01:00
95ddcbaf13 🔪🐛 Fix shutdown being called before init, fix duplicate SIGNIT catch
All checks were successful
Deploy application / deploy (push) Successful in 16s
2025-02-13 21:15:02 +01:00
4367c24fb0 🌟 Refactor
- Moved mappings into Sb1 impl
- Moved Actual types to @common
- Moved createDirIfMissing to respective functions
- Refactored main into multiple functions
- Moved create db into Sb1impl and close
- Log requests on info
2025-02-13 21:07:30 +01:00
06cc89f762 💾 Volume for cache, default values for envs in compose
All checks were successful
Deploy application / deploy (push) Successful in 3s
2025-02-09 13:54:35 +01:00
b6daf4268c 🚀 Init and shutdown Actual on job
- Renamed daily function to moveTransactions
- testConnections method to verify connection immediately
2025-02-09 13:34:00 +01:00
db30129c30 ☝ Update dependencies
All checks were successful
Deploy application / deploy (push) Successful in 9s
2025-02-09 13:12:02 +01:00
3c6cb193eb 🔪🐛 Fixed pnpm in Dockerfile, moved config to src
All checks were successful
Deploy application / deploy (push) Successful in 10s
2025-02-09 13:02:02 +01:00
c5b1ec20d6 🧹 Moved Sb1 API to separate workspace and created common workspace
- Created common workspace
- Create Sparebank1Api workspace
- Moved logger to common
- Moved SB1 types to types.ts
- Logger will avoid duplicating first line when capturing console.logs
- Updated imports and added type keyword
- Added nonUniqueId type
2025-02-09 12:35:08 +01:00
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
41cb92cce5 Removed transaction logger
All checks were successful
Deploy application / deploy (push) Successful in 3s
2025-01-31 17:06:36 +01:00
18a0fbfac8 Relative from and to date in config, changed default to 3 days
All checks were successful
Deploy application / deploy (push) Successful in 7s
2025-01-31 16:58:02 +01:00
752bdbceb4 Cleared status from API, docker script
All checks were successful
Deploy application / deploy (push) Successful in 6s
2025-01-27 21:30:56 +01:00
61f0153319 Fix typo...
All checks were successful
Deploy application / deploy (push) Successful in 6s
2025-01-26 19:38:08 +01:00
d618438b14 Fix DB_DIRECTORY env is empty in Docker compose
Some checks failed
Deploy application / deploy (push) Failing after 6s
2025-01-26 19:36:17 +01:00
9850017e3a 🐋 Docker volume for Sqlite
Some checks failed
Deploy application / deploy (push) Failing after 7s
- Moved database to subdir specified by env
- Default data dir /data
- Move loggers to cronJob onTick
- Added volume for data dir in Docker compose
- Create any missing dir specified by env
2025-01-26 19:29:43 +01:00
aaa85e99cb 🐋 Docker and Gitea Workflow
All checks were successful
Deploy application / deploy (push) Successful in 19s
- Moved tsx to dependencies as node TS support is 💩
- Renamed start-once to run-once
- TODOs
2025-01-26 17:41:44 +01:00
2e73baf98b ✏ README, fix start-once bug and refactor
- Added some configuration and running to README
- Refactored some code
- Fixed exception when stopping a start-once script
- Only allow running with pnpm
- Moved transactions into sparebank1Api.ts
- Formatted
2025-01-25 22:30:52 +01:00
4977e7ad6a 🔨 Run once, graceful shutdown, db filename in env
- Refactored toISODateString function
- Added Db filename to env
- Added getOrDefault function for fetching envs, replaced LOG_LEVEL with getOrDefault
- Added script to run job once then exit
- Catch SIGINT signal and do a graceful shutdown
2025-01-25 21:12:49 +01:00
b61903f5c8 🎉 Working prototype
- Added missing field payee_name to TransactionEntity type
- Date function to convert DayJs to DateString
- Temp disabled cronjob for testing
- Fixed mapping to ActualModel
- fetchToken db function returns DayJs object for date
- Fixed fetching tokens from db
- Logging
- Fixed fetch previous day transactions
- Fixed token refresh
- Fixed stub based on model changes
2025-01-25 18:01:47 +01:00
9a00592a7a GitIgnore database 2025-01-23 21:06:42 +01:00
4a773e4b43 🔑 Store tokens in Sqllite, moved queries, other fixes
- Create cache dir if missing
- Moved Sqlite queries to queries.ts
- Updated dependencies
- Added pino-pretty to dev-dependencies
- Changed Sqlite to store tokens as separate rows
- Removed in-memory storage of tokens
- isValidToken function
- Throw Exception if refresh token is present but invalid
- Fixed fetch query in smn http file
2025-01-22 21:00:04 +01:00
3bf354b4bf SQLite
Moved DB queries to separate file
Moved Sparebank1 API call to separate file
Create database tokens table if it doesn't exist

Signed-off-by: Martin Berg Alstad <git@martials.no>
2024-12-26 14:08:09 +01:00
8854a22b40 Added better-sqlite3 dep and created default db
Signed-off-by: Martin Berg Alstad <git@martials.no>
2024-12-26 12:49:54 +01:00
6650e2cd2b Removed
- accessToken and refreshToken methods from interface
- accessToken param from transactionsPastDay
- Unused env variables from config.ts

Added
- Initial Refresh token to env
- Dayjs library for working with dates

Implemented
- getAccessToken
- getRefreshToken
- fetchNewRefreshToken
- transactionsPastDay

Signed-off-by: Martin Berg Alstad <git@martials.no>
2024-12-25 21:06:42 +01:00
480c0356f9 Fixes
- Added Actual account ids and log level to .env.example.
- Fixed timestamp error by downloading the budget after init.
- Hardcoded date in test.
- Separate logging file for configurations.
- Organized test
- More logging in main
- Fixed wrong paths for some files
- Load a .env.test.local file when running tests

Signed-off-by: Martin Berg Alstad <git@martials.no>
2024-12-23 16:47:07 +01:00
29b394baf4 Moved sparebank1.ts to bank dir
Signed-off-by: Martin Berg Alstad <git@martials.no>
2024-12-22 16:06:20 +01:00
966c5f50b3 Fix broken lockfile
Fix @ module path
2024-12-22 13:14:55 +01:00
c43bff3e15 testing with jest 2024-12-16 21:25:36 +00:00
9ed0a19393 Changed:
- Env key to be more generic
- Cache directory to .cache
- Multiply bank amount by 100 to get correct conversion rate

Removed:
- Unused functions in Actual.ts

Added:
- Test for main functionality
- BankStub for testing
- Added imported_id to Actual Transaction to avoid duplicates
2024-12-01 20:48:42 +01:00
cc325b9f08 Added:
- Logging library
- Account Ids to .env
- Split logic in main function
2024-12-01 19:35:45 +01:00
39 changed files with 5138 additions and 450 deletions

10
.dockerignore Normal file
View File

@ -0,0 +1,10 @@
.cache
.idea
httpRequests
.env.*
*.sqlite
jest.config.ts
**/node_modules
.git
.gitignore
*.md

View File

@ -1,9 +1,18 @@
# Actual Budget
ACTUAL_BUDGET_ID=your-budget-id
ACTUAL_SYNC_ID=your-sync-id
ACTUAL_SERVER_URL=your-server-url
ACTUAL_SERVER_URL=http://your-server-url:5006
ACTUAL_PASSWORD=your-password
# Sparebank1
SPAREBANK1_OAUTH_CLIENT_ID=your-client-id
SPAREBANK1_OAUTH_CLIENT_SECRET=your-client-secret
SPAREBANK1_OAUTH_STATE=your-state
SPAREBANK1_OAUTH_REDIRECT_URI=your-redirect-uri
ACTUAL_ACCOUNT_IDS=your-account-id1,your-account-id2
ACTUAL_DATA_DIR=.cache
# Bank
BANK_INITIAL_REFRESH_TOKEN=initial-valid-refresh-token
BANK_OAUTH_CLIENT_ID=your-client-id
BANK_OAUTH_CLIENT_SECRET=your-client-secret
BANK_ACCOUNT_IDS=your-account-id1,your-account-id2
# Configuration
LOG_LEVEL=info# trace | error | warn | info | debug | trace
DB_DIRECTORY=data# Relative path, must not start or end with /
DB_FILENAME=default
TRANSACTION_RELATIVE_FROM_DATE=4
TRANSACTION_RELATIVE_TO_DATE=3

View File

@ -0,0 +1,35 @@
name: Deploy application
on:
push:
branches: [main]
jobs:
deploy:
runs-on: host
env:
# Actual budget
ACTUAL_BUDGET_ID: ${{ secrets.ACTUAL_BUDGET_ID }}
ACTUAL_SYNC_ID: ${{ secrets.ACTUAL_SYNC_ID }}
ACTUAL_SERVER_URL: ${{ secrets.ACTUAL_SERVER_URL }}
ACTUAL_PASSWORD: ${{ secrets.ACTUAL_PASSWORD }}
ACTUAL_ACCOUNT_IDS: ${{ secrets.ACTUAL_ACCOUNT_IDS }}
ACTUAL_DATA_DIR: ${{ vars.ACTUAL_DATA_DIR }}
# Bank
BANK_INITIAL_REFRESH_TOKEN: ${{ secrets.BANK_INITIAL_REFRESH_TOKEN }}
BANK_OAUTH_CLIENT_ID: ${{ secrets.BANK_OAUTH_CLIENT_ID }}
BANK_OAUTH_CLIENT_SECRET: ${{ secrets.BANK_OAUTH_CLIENT_SECRET }}
BANK_ACCOUNT_IDS: ${{ secrets.BANK_ACCOUNT_IDS }}
# Configuration
LOG_LEVEL: ${{ vars.LOG_LEVEL }}
DB_DIRECTORY: ${{ vars.DB_DIRECTORY }}
DB_FILENAME: ${{ vars.DB_FILENAME }}
TRANSACTION_RELATIVE_FROM_DATE: ${{ vars.TRANSACTION_RELATIVE_FROM_DATE || 'N/A' }}
TRANSACTION_RELATIVE_TO_DATE: ${{ vars.TRANSACTION_RELATIVE_TO_DATE || 'N/A' }}
steps:
- name: Check out repository code
uses: actions/checkout@v4
- name: Run docker-compose
run: docker compose up -d --build

7
.gitignore vendored
View File

@ -12,7 +12,7 @@ lerna-debug.log*
# Caches
data/cache/*
.cache
# Diagnostic reports (https://nodejs.org/api/report.html)
@ -174,3 +174,8 @@ dist
# Finder (MacOS) folder config
.DS_Store
# SQLite
*.sqlite
*.sqlite-shm
*.sqlite-wal

14
Dockerfile Normal file
View File

@ -0,0 +1,14 @@
FROM node:22-slim
LABEL authors="Martin Berg Alstad"
COPY . ./app
WORKDIR ./app
ENV PNPM_HOME="/pnpm"
ENV PATH="$PNPM_HOME:$PATH"
RUN corepack enable pnpm
RUN corepack prepare pnpm@9.15.3 --activate
RUN npm i -g corepack@latest
RUN --mount=type=cache,id=pnpm,target=/pnpm/store pnpm install --prod --recursive --frozen-lockfile
ENTRYPOINT ["pnpm", "start-prod"]

View File

@ -1,3 +1,26 @@
# Sparebank1 ActualBudget Integration
🔧 WIP!
### Setting up the environment
In order to start the application, an `.env.local` file must be present at the root level. The possible and required
fields
can be found in the [.env.example](.env.example) file and `config.ts`.
For running integration tests, the `.env.test.local` file must be present at the root level, with Actual fields present.
HTTP requests can be used from an IDE via the .http files. Secrets must be placed in a file called
`http-client.private.env.json` in the [httpRequests](httpRequests) directory. See the .http files for required values.
### Running the application
Start the application using a CronJob that runs at a given time. Can be stopped using an interrupt (^C)
```shell
pnpm start
```
Start the application without a CronJob, it will run once, then shutdown.
```shell
pnpm run-once
```

View File

@ -1,27 +0,0 @@
import assert from "node:assert"
import dotenv from "dotenv"
dotenv.config()
export const ACTUAL_BUDGET_ID = getOrThrow("ACTUAL_BUDGET_ID")
export const ACTUAL_SYNC_ID = getOrThrow("ACTUAL_SYNC_ID")
export const ACTUAL_SERVER_URL = getOrThrow("ACTUAL_SERVER_URL")
export const ACTUAL_PASSWORD = getOrThrow("ACTUAL_PASSWORD")
export const ACTUAL_DATA_DIR = "data/cache"
export const SPAREBANK1_OAUTH_CLIENT_ID = getOrThrow(
"SPAREBANK1_OAUTH_CLIENT_ID",
)
export const SPAREBANK1_OAUTH_CLIENT_SECRET = getOrThrow(
"SPAREBANK1_OAUTH_CLIENT_SECRET",
)
export const SPAREBANK1_OAUTH_REDIRECT_URI = getOrThrow(
"SPAREBANK1_OAUTH_REDIRECT_URI",
)
export const SPAREBANK1_OAUTH_STATE = getOrThrow("SPAREBANK1_OAUTH_STATE")
function getOrThrow(key: string): string {
const value = process.env[key]
assert(value, `Missing environment variable: ${key}`)
return value
}

30
docker-compose.yml Normal file
View File

@ -0,0 +1,30 @@
services:
server:
container_name: actual_sparebank1_cronjob
restart: unless-stopped
build:
context: .
environment:
- ACTUAL_BUDGET_ID
- ACTUAL_SYNC_ID
- ACTUAL_SERVER_URL
- ACTUAL_PASSWORD
- ACTUAL_ACCOUNT_IDS
- ACTUAL_DATA_DIR
- BANK_INITIAL_REFRESH_TOKEN
- BANK_OAUTH_CLIENT_ID
- BANK_OAUTH_CLIENT_SECRET
- BANK_ACCOUNT_IDS
- LOG_LEVEL
- DB_DIRECTORY
- DB_FILENAME
- TRANSACTION_RELATIVE_FROM_DATE
- TRANSACTION_RELATIVE_TO_DATE
volumes:
- cache:/app/${ACTUAL_DATA_DIR:-.cache}
- data:/app/${DB_DIRECTORY:-data}
# TODO change volume name from hostexecutor-*
volumes:
cache:
data:

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

@ -11,13 +11,12 @@ GET {{oauthBaseUrl}}/authorize?client_id={{sparebank1OauthClientId}}&
### OAuth2 Access Token Request
# Refresh token is valid for 365 days
# Access token is valid for 10 minutes
@authenticationCode=<insert code here>
POST {{oauthBaseUrl}}/token
Content-Type: application/x-www-form-urlencoded
client_id = {{sparebank1OauthClientId}} &
client_secret = {{sparebank1OauthClientSecret}} &
code = {{authenticationCode}} &
code = {{sparebank1OauthAuthCode}} &
grant_type = authorization_code &
state = {{sparebank1OauthState}} &
redirect_uri = {{sparebank1OauthRedirectUri}}
@ -43,7 +42,6 @@ grant_type = refresh_token
%}
### Hello World from Sparebank1
GET https://api.sparebank1.no/common/helloworld
Authorization: Bearer {{ACCESS_TOKEN}}
Accept: application/vnd.sparebank1.v1+json; charset=utf-8
@ -52,9 +50,9 @@ Accept: application/vnd.sparebank1.v1+json; charset=utf-8
GET {{bankingBaseUrl}}/accounts
Authorization: Bearer {{ACCESS_TOKEN}}
### Fetch all transactions of the previous day
# TODO date search not working?
GET {{bankingBaseUrl}}/transactions?accountKey={{brukskontoAccountKey}}&fromDate=2024-11-14&
toDate=2024-11-15
### Fetch all transactions of specific days (inclusive)
GET {{bankingBaseUrl}}/transactions?accountKey={{accountKey1}}&accountKey={{accountKey2}}&
fromDate=2025-01-20&
toDate=2025-01-24
Authorization: Bearer {{ACCESS_TOKEN}}
Accept: application/vnd.sparebank1.v1+json; charset=utf-8

22
jest.config.ts Normal file
View File

@ -0,0 +1,22 @@
import type { JestConfigWithTsJest } from "ts-jest"
const config: JestConfigWithTsJest = {
verbose: true,
transform: {
"^.+\\.ts?$": [
"ts-jest",
{
useESM: true,
},
],
},
extensionsToTreatAsEsm: [".ts"],
moduleNameMapper: {
"^(\\.{1,2}/.*)\\.js$": "$1",
// Resolve @/ module paths
"@/(.*)": "<rootDir>/src/$1",
},
setupFiles: ["<rootDir>/config.ts"],
}
export default config

1
modules.d.ts vendored
View File

@ -1 +0,0 @@
// TODO

View File

@ -2,25 +2,36 @@
"name": "sparebank1_actual_budget_integration",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"start": "node --import=tsx ./src/main.ts",
"test": "echo \"Error: no test specified\" && exit 1",
"start": "dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | ./packages/common/node_modules/pino-pretty/bin.js",
"start-prod": "node --import=tsx ./src/main.ts",
"run-once": "ONCE=true dotenvx run --env-file=.env.local -- node --import=tsx ./src/main.ts | ./packages/common/node_modules/pino-pretty/bin.js",
"test": "dotenvx run --env-file=.env.test.local -- node --experimental-vm-modules node_modules/jest/bin/jest.js | ./packages/common/node_modules/pino-pretty/bin.js",
"docker-build": "DB_DIRECTORY=data docker compose --env-file .env.local up -d --build",
"format": "prettier --write \"./**/*.{js,mjs,ts,md,json}\""
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@actual-app/api": "^24.11.0",
"cron": "^3.2.1",
"dotenv": "^16.4.5",
"prettier": "^3.3.3"
"@actual-app/api": "^25.7.1",
"@dotenvx/dotenvx": "^1.45.2",
"better-sqlite3": "^12.2.0",
"cron": "^4.3.1",
"dayjs": "^1.11.13",
"dotenv": "^17.0.1",
"prettier": "^3.6.2",
"tsx": "^4.20.3"
},
"devDependencies": {
"@types/node": "^22.9.0",
"tsx": "^4.19.2",
"typescript": "^5.6.3"
"@jest/globals": "^29.7.0",
"@types/better-sqlite3": "^7.6.13",
"@types/jest": "^30.0.0",
"@types/node": "^24.0.10",
"jest": "^30.0.4",
"ts-jest": "^29.4.0",
"ts-node": "^10.9.2",
"typescript": "^5.8.3"
},
"prettier": {
"semi": false,

3
packages/common/date.ts Normal file
View File

@ -0,0 +1,3 @@
import { type Dayjs } from "dayjs"
export const toISODateString = (day: Dayjs): string => day.format("YYYY-MM-DD")

21
packages/common/logger.ts Normal file
View File

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

View File

@ -0,0 +1,12 @@
{
"name": "common",
"version": "1.0.0",
"description": "",
"license": "ISC",
"dependencies": {
"pino": "^9.6.0"
},
"devDependencies": {
"pino-pretty": "^13.0.0"
}
}

66
packages/common/types.ts Normal file
View File

@ -0,0 +1,66 @@
import type { Dayjs } from "dayjs"
import type { UUID } from "node:crypto"
import { TransactionEntity } from "@actual-app/api/@types/loot-core/src/types/models"
/**
* Defines how to interact with the bank
*/
export interface Bank {
/**
* Fetch all transactions in the specified days, from the given accounts
* @param interval Which days to fetch transactions for
* @param accountKeys The id of the accounts to fetch transactions from
* @returns An array of all transactions
*/
fetchTransactions: (
interval: Interval,
...accountKeys: ReadonlyArray<string>
) => Promise<ReadonlyArray<ActualTransaction>>
/**
* Shutdown resources
*/
shutdown: () => Promise<void> | void
}
export interface Interval {
fromDate: Dayjs
toDate: Dayjs
}
/**
* Describes how to interact with ActualBudget
*/
export interface Actual {
/**
* Import transactions following the rules defined in the ActualBudget instance
* If the transactions exists, it will be updated, or no change should be done.
* @param accountId The ActualBudget id to upload to
* @param transactions The transactions to import
* @returns An object describing what changed
*/
importTransactions: (
accountId: UUID,
transactions: Iterable<ActualTransaction>,
) => Promise<ImportTransactionsResponse>
/**
* Disconnect from ActualBudget and release resources
*/
shutdown: () => Promise<void>
}
export interface ActualTransaction extends TransactionEntity {
account: UUID
payee_name?: string
}
export interface ImportTransactionsResponse {
errors?: Message[]
added: number
updated: number
}
export interface Message {
message: string
}

View File

@ -0,0 +1,83 @@
import Database from "better-sqlite3"
import dayjs from "dayjs"
import type { OAuthTokenResponse } from "@sb1/types.ts"
import type {
TokenKey,
TokenResponse,
TokenResponseRaw,
} from "@sb1impl/db/types.ts"
import logger from "@common/logger.ts"
export function createDb(filepath: string) {
const db = new Database(filepath)
logger.info(`Started Sqlite database at '${filepath}'`)
db.pragma("journal_mode = WAL")
db.exec(
"CREATE TABLE IF NOT EXISTS tokens ('key' VARCHAR PRIMARY KEY, token VARCHAR NOT NULL, expires_at DATETIME NOT NULL)",
)
return db
}
export function insertTokens(
db: Database.Database,
oAuthToken: OAuthTokenResponse,
): void {
insertAccessToken(db, oAuthToken.access_token, oAuthToken.expires_in)
insertRefreshToken(
db,
oAuthToken.refresh_token,
oAuthToken.refresh_token_absolute_expires_in,
)
}
function insertAccessToken(
db: Database.Database,
accessToken: string,
expiresIn: number,
) {
insert(db, "access-token", accessToken, expiresIn)
}
function insertRefreshToken(
db: Database.Database,
refreshToken: string,
expiresIn: number,
): void {
insert(db, "refresh-token", refreshToken, expiresIn)
}
function insert(
db: Database.Database,
key: TokenKey,
token: string,
expiresIn: number,
): void {
db.prepare("INSERT OR REPLACE INTO tokens VALUES (?, ?, ?)").run(
key,
token,
dayjs().add(expiresIn, "seconds").toISOString(),
)
}
export function fetchToken(
db: Database.Database,
tokenKey: TokenKey,
): TokenResponse | null {
const response = db
.prepare("SELECT * FROM tokens WHERE key = ?")
.get(tokenKey) as TokenResponseRaw | null
return (
response && {
...response,
expires_at: dayjs(response.expires_at),
}
)
}
export function clearTokens(db: Database.Database): void {
db.prepare("DELETE FROM tokens WHERE key in ( ?, ? )").run([
"access-token",
"refresh-token",
] as TokenKey[])
}

View File

@ -0,0 +1,13 @@
import type { Dayjs } from "dayjs"
export type TokenResponse = {
key: TokenKey
token: string
expires_at: Dayjs
}
export type TokenResponseRaw = {
[K in keyof TokenResponse]: K extends "expires_at" ? string : TokenResponse[K]
}
export type TokenKey = "access-token" | "refresh-token"

View File

@ -0,0 +1,43 @@
import { ACTUAL_ACCOUNT_IDS, BANK_ACCOUNT_IDS } from "@/config.ts"
import { toISODateString } from "@common/date.ts"
import dayjs from "dayjs"
import type { ActualTransaction } from "@common/types.ts"
import type { SB1Transaction } from "@sb1/types.ts"
import type { UUID } from "node:crypto"
export function bankTransactionIntoActualTransaction(
transaction: SB1Transaction,
): ActualTransaction {
return {
id: transaction.id,
// Transactions with the same id will be ignored
imported_id: transaction.nonUniqueId,
account: getActualAccountId(transaction),
// The value without decimals
amount: Math.floor(transaction.amount * 100),
date: toISODateString(dayjs(transaction.date)),
payee_name: transaction.cleanedDescription,
cleared: isCleared(transaction),
}
}
export function isCleared(transaction: SB1Transaction): boolean {
const id = Number(transaction.nonUniqueId)
return transaction.bookingStatus === "BOOKED" && !Number.isNaN(id) && id > 0
}
function getActualAccountId(transcation: SB1Transaction): 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
}
}
throw new Error(
"Failed to find ActualAccountId, length of BANK_ACCOUNT_IDS and ACTUAL_ACCOUNT_IDS must match",
)
}

View File

@ -0,0 +1,104 @@
import * as Transactions from "@sb1/transactions.ts"
import * as Oauth from "@sb1/oauth.ts"
import {
BANK_INITIAL_REFRESH_TOKEN,
BANK_OAUTH_CLIENT_ID,
BANK_OAUTH_CLIENT_SECRET,
DB_DIRECTORY,
DB_FILENAME,
} from "@/config.ts"
import {
clearTokens,
createDb,
fetchToken,
insertTokens,
} from "@sb1impl/db/queries.ts"
import { bankTransactionIntoActualTransaction } from "./mappings.ts"
import { createDirIfMissing } from "@/fs.ts"
import logger from "@common/logger.ts"
import dayjs from "dayjs"
import type { ActualTransaction, Bank, Interval } from "@common/types.ts"
import type { TokenResponse } from "@sb1impl/db/types.ts"
import type { OAuthTokenResponse } from "@sb1/types.ts"
import type { Database } from "better-sqlite3"
export class Sparebank1Impl implements Bank {
private readonly db: Database
constructor() {
createDirIfMissing(DB_DIRECTORY)
const databaseFilePath = `${DB_DIRECTORY}/${DB_FILENAME}.sqlite`
this.db = createDb(databaseFilePath)
}
// TODO if not cleared rerun later
async fetchTransactions(
interval: Interval,
...accountKeys: ReadonlyArray<string>
): Promise<ReadonlyArray<ActualTransaction>> {
const response = await Transactions.list(
await this.getAccessToken(),
accountKeys,
interval,
)
return response.transactions
.map((transaction) => {
const actualTransaction =
bankTransactionIntoActualTransaction(transaction)
return actualTransaction.cleared === true ? actualTransaction : null
})
.filter((transaction) => transaction !== null)
}
shutdown(): void {
this.db.close()
}
private async getAccessToken(): Promise<string> {
const accessToken = fetchToken(this.db, "access-token")
if (accessToken && this.isValidToken(accessToken)) {
return accessToken.token
}
const response = await this.fetchNewTokens()
return response.access_token
}
private isValidToken(tokenResponse: TokenResponse): boolean {
// TODO make sure the same timezone is used. Db uses UTC
return dayjs().isBefore(tokenResponse.expires_at)
}
private async getRefreshToken(): Promise<string> {
const tokenResponse = fetchToken(this.db, "refresh-token")
if (!tokenResponse) {
return BANK_INITIAL_REFRESH_TOKEN
} else if (this.isValidToken(tokenResponse)) {
return tokenResponse.token
}
logger.warn("Refresh token expired, deleting tokens from database")
clearTokens(this.db)
throw new Error("Refresh token is expired. Create a new one")
}
private async fetchNewTokens(): Promise<OAuthTokenResponse> {
const refreshToken = await this.getRefreshToken()
const result = await Oauth.refreshToken(
BANK_OAUTH_CLIENT_ID,
BANK_OAUTH_CLIENT_SECRET,
refreshToken,
)
if (result.status === "failure") {
throw new Error(`Failed to fetch refresh token: '${result.data}'`)
}
const oAuthToken = result.data
insertTokens(this.db, oAuthToken)
return oAuthToken
}
}

View File

@ -0,0 +1,12 @@
import type { Failure, Success } from "./types"
export const baseUrl = "https://api.sparebank1.no"
export const success = <T>(data: T): Success<T> => ({
status: "success",
data: data,
})
export const failure = <T>(data: T): Failure<T> => ({
status: "failure",
data: data,
})

View File

@ -0,0 +1,30 @@
import type { OAuthTokenResponse, Result } from "./types"
import * as querystring from "node:querystring"
import { baseUrl, failure, success } from "./common"
import logger from "@common/logger"
export async function refreshToken(
clientId: string,
clientSecret: string,
refreshToken: string,
): Promise<Result<OAuthTokenResponse, string>> {
const queries = querystring.stringify({
client_id: clientId,
client_secret: clientSecret,
refresh_token: refreshToken,
grant_type: "refresh_token",
})
const url = `${baseUrl}/oauth/token?${queries}`
logger.debug(`Sending POST request to url: '${url}'`)
const response = await fetch(url, {
method: "post",
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
})
logger.debug(`Received response with status '${response.status}'`)
if (!response.ok) {
return failure(await response.text())
}
return success(await response.json())
}

View File

@ -0,0 +1,6 @@
{
"name": "packages",
"version": "1.0.0",
"description": "",
"license": "ISC"
}

View File

@ -0,0 +1,36 @@
import type { TransactionResponse } from "./types"
import * as querystring from "node:querystring"
import { toISODateString } from "@common/date"
import logger from "@common/logger"
import { baseUrl } from "./common"
import type { Interval } from "@common/types.ts"
export async function list(
accessToken: string,
accountKeys: string | ReadonlyArray<string>,
interval?: Interval,
): Promise<TransactionResponse> {
const queryString = querystring.stringify({
accountKey: accountKeys,
...(interval && {
fromDate: toISODateString(interval.fromDate),
toDate: toISODateString(interval.toDate),
}),
})
const url = `${baseUrl}/personal/banking/transactions?${queryString}`
logger.info(`GET '${url}'`)
const response = await fetch(url, {
headers: {
Authorization: `Bearer ${accessToken}`,
Accept: "application/vnd.sparebank1.v1+json;charset=utf-8",
},
})
logger.debug(`Received response with status '${response.status}'`)
if (response.ok) {
return response.json()
} else {
logger.warn(await response.json())
return { transactions: [] }
}
}

View File

@ -0,0 +1,40 @@
export type Success<T> = { status: "success"; data: T }
export type Failure<T> = { status: "failure"; data: T }
export type Result<OK, Err> = Success<OK> | Failure<Err>
export interface OAuthTokenResponse {
access_token: string
expires_in: number
refresh_token_expires_in: number
refresh_token_absolute_expires_in: number
token_type: "Bearer"
refresh_token: string
}
export type BookingStatus = "PENDING" | "BOOKED"
/**
* 18-character unique ID used to identify a transaction
* The value is "000000000000000000" until the transaction is booked, and might be set a few days later
*/
export type NonUniqueId = "000000000000000000" | `${number}`
export interface SB1Transaction {
id: string
nonUniqueId: NonUniqueId
// The Id of the account
accountKey: string
// Unix time
date: number
// Amount in NOK
amount: number
cleanedDescription: string
remoteAccountName: string
bookingStatus: BookingStatus
[key: string]: string | number | boolean | unknown
}
export interface TransactionResponse {
transactions: ReadonlyArray<SB1Transaction>
}

4368
pnpm-lock.yaml generated

File diff suppressed because it is too large Load Diff

2
pnpm-workspace.yaml Normal file
View File

@ -0,0 +1,2 @@
packages:
- "packages/*"

View File

@ -4,33 +4,21 @@ import {
ACTUAL_PASSWORD,
ACTUAL_SERVER_URL,
ACTUAL_SYNC_ID,
} from "../config.ts"
import type { TransactionEntity } from "@actual-app/api/@types/loot-core/types/models"
import { type UUID } from "node:crypto"
export interface Actual {
importTransactions: (
accountId: UUID,
transactions: ReadonlyArray<TransactionEntity>,
) => Promise<ImportTransactionsResponse>
shutdown: () => Promise<void>
}
export interface Message {
message: string
}
export interface ImportTransactionsResponse {
errors?: Message[]
added: number
updated: number
}
} from "@/config.ts"
import logger from "@common/logger.ts"
import type { UUID } from "node:crypto"
import type {
Actual,
ActualTransaction,
ImportTransactionsResponse,
} from "@common/types.ts"
import { createDirIfMissing } from "@/fs.ts"
export class ActualImpl implements Actual {
private constructor() {}
static async init(): Promise<Actual> {
createDirIfMissing(ACTUAL_DATA_DIR)
await actual.init({
// Budget data will be cached locally here, in subdirectories for each file.
dataDir: ACTUAL_DATA_DIR,
@ -39,42 +27,40 @@ export class ActualImpl implements Actual {
// This is the password you use to log into the server
password: ACTUAL_PASSWORD,
})
logger.info(`Initialized ActualBudget API for ${ACTUAL_SERVER_URL}`)
await this.downloadBudget()
return new ActualImpl()
}
/**
* Attempts to connect then immediatly shutsdown the connection
* @exception error If connection fails
*/
static async testConnection(): Promise<void> {
let actual: Actual | undefined
logger.info("Testing ActualBudget connection")
try {
actual = await ActualImpl.init()
} finally {
await actual?.shutdown()
logger.info("Finished testing ActualBudget connection")
}
}
async importTransactions(
accountId: UUID,
transactions: ReadonlyArray<TransactionEntity>,
transactions: Iterable<ActualTransaction>,
): Promise<ImportTransactionsResponse> {
return await actual.importTransactions(accountId, transactions)
return actual.importTransactions(accountId, transactions)
}
async shutdown() {
return await actual.shutdown()
async shutdown(): Promise<void> {
logger.info(`Shutting down ActualBudget API for ${ACTUAL_SERVER_URL}`)
return actual.shutdown()
}
private static async downloadBudget(): Promise<void> {
await actual.downloadBudget(ACTUAL_SYNC_ID)
logger.info(`Downloaded budget`)
}
}
export async function init() {
return await actual.init({
// Budget data will be cached locally here, in subdirectories for each file.
dataDir: ACTUAL_DATA_DIR,
// This is the URL of your running server
serverURL: ACTUAL_SERVER_URL,
// This is the password you use to log into the server
password: ACTUAL_PASSWORD,
})
}
export async function downloadBudget() {
const something = await actual.downloadBudget(ACTUAL_SYNC_ID)
console.log("downloadBudget", something)
return something
}
export async function getAccounts() {
return await actual.getAccounts()
}
export async function shutdown() {
await actual.shutdown()
}

55
src/config.ts Normal file
View File

@ -0,0 +1,55 @@
import assert from "node:assert"
import dotenv from "dotenv"
dotenv.config()
// Actual
export const ACTUAL_SYNC_ID = getOrThrow("ACTUAL_SYNC_ID")
export const ACTUAL_SERVER_URL = getOrThrow("ACTUAL_SERVER_URL")
export const ACTUAL_PASSWORD = getOrThrow("ACTUAL_PASSWORD")
export const ACTUAL_ACCOUNT_IDS = getArrayOrThrow("ACTUAL_ACCOUNT_IDS")
export const ACTUAL_DATA_DIR = getOrDefault("ACTUAL_DATA_DIR", ".cache")
// Bank
export const BANK_INITIAL_REFRESH_TOKEN = getOrThrow(
"BANK_INITIAL_REFRESH_TOKEN",
)
export const BANK_OAUTH_CLIENT_ID = getOrThrow("BANK_OAUTH_CLIENT_ID")
export const BANK_OAUTH_CLIENT_SECRET = getOrThrow("BANK_OAUTH_CLIENT_SECRET")
export const BANK_ACCOUNT_IDS = getArrayOrThrow("BANK_ACCOUNT_IDS")
// Configuration
export const DB_DIRECTORY = getOrDefault("DB_DIRECTORY", "data")
export const DB_FILENAME = getOrDefault("DB_FILENAME", "default")
export const LOG_LEVEL = getOrDefault("LOG_LEVEL", "info")
// TODO default to fetch 1 day
// Relative number of days in the past to start fetching transactions from
export const TRANSACTION_RELATIVE_FROM_DATE = getNumberOrDefault(
"TRANSACTION_RELATIVE_FROM_DATE",
4,
)
// Relative number of days in the past to end fetching transactions from
export const TRANSACTION_RELATIVE_TO_DATE = getNumberOrDefault(
"TRANSACTION_RELATIVE_TO_DATE",
3,
)
// Utility functions
function getOrDefault(key: string, def: string): string {
return process.env[key] || def
}
function getOrThrow(key: string): string {
const value = process.env[key]
assert(value, `Missing environment variable: ${key}`)
return value
}
function getArrayOrThrow(key: string): ReadonlyArray<string> {
return getOrThrow(key).split(",")
}
function getNumberOrDefault(key: string, def: number): number {
const num = Number(process.env[key])
return Number.isNaN(num) ? def : num
}

View File

@ -1,4 +1,5 @@
import { CronJob } from "cron"
import logger from "@common/logger.ts"
/**
* Run a function every day at 1 AM, Oslo time.
@ -8,7 +9,11 @@ import { CronJob } from "cron"
export function cronJobDaily(onTick: () => Promise<void>): CronJob {
return CronJob.from({
cronTime: "0 0 1 * * *",
onTick,
onTick: async () => {
logger.info("Starting daily job")
await onTick()
logger.info("Finished daily job")
},
start: true,
timeZone: "Europe/Oslo",
})

10
src/fs.ts Normal file
View File

@ -0,0 +1,10 @@
import * as fs from "node:fs"
import logger from "@common/logger"
// TODO move to common
export function createDirIfMissing(directory: string): void {
if (!fs.existsSync(directory)) {
logger.info(`Missing '${directory}', creating...`)
fs.mkdirSync(directory, { recursive: true })
}
}

View File

@ -1,33 +1,127 @@
import { type Actual, ActualImpl } from "@/actual.ts"
import { ActualImpl } from "@/actual.ts"
import { cronJobDaily } from "@/cron.ts"
import { type Bank, Sparebank1Impl } from "@/sparebank1.ts"
import { transactionIntoActualTransaction } from "@/mappings.ts"
import {
BANK_ACCOUNT_IDS,
TRANSACTION_RELATIVE_FROM_DATE,
TRANSACTION_RELATIVE_TO_DATE,
} from "@/config.ts"
import logger from "@common/logger.ts"
import type { UUID } from "node:crypto"
import { CronJob } from "cron"
import dayjs from "dayjs"
import type { Actual, Bank, Interval } from "@common/types.ts"
import { Sparebank1Impl } from "@sb1impl/sparebank1.ts"
async function daily(actual: Actual, bank: Bank): Promise<() => Promise<void>> {
return async () => {
console.log("Wake up! It's 1 AM!")
// Fetch transactions from the bank
const transactions = await bank.transactionsPastDay(
"my_account",
"my_access_token",
)
// TODO move tsx to devDependency. Requires ts support for Node with support for @ alias
// TODO verbatimSyntax in tsconfig, conflicts with jest
// TODO store last fetched date in db, and refetch from that date, if app has been offline for some time
// TODO account? id or name?
const actualTransactions = transactions.map((transaction) =>
transactionIntoActualTransaction(transaction, ""),
)
async function main(): Promise<void> {
logger.info("Starting application")
const bank = new Sparebank1Impl()
// TODO Import transactions into Actual
// If multiple accounts, loop over them
// Get account ID from mapper
await actual.importTransactions("a-b-c-d-e", actualTransactions)
if (process.env.ONCE) {
return await runOnce(bank)
}
await ActualImpl.testConnection()
await runCronJob(bank)
}
export async function moveTransactions(
actual: Actual,
bank: Bank,
): Promise<void> {
const actualTransactions = await bank.fetchTransactions(
relativeInterval(),
...BANK_ACCOUNT_IDS,
)
logger.info(`Fetched ${actualTransactions.length} transactions`)
if (actualTransactions.length === 0) {
logger.debug("No transactions to import, skipping")
return
}
const transactionsByAccount = Object.groupBy(
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",
)
}
function relativeInterval(): Interval {
const today = dayjs()
return {
fromDate: today.subtract(TRANSACTION_RELATIVE_FROM_DATE, "days"),
toDate: today.subtract(TRANSACTION_RELATIVE_TO_DATE, "days"),
}
}
async function main(): Promise<void> {
async function runOnce(bank: Bank) {
const actual = await ActualImpl.init()
cronJobDaily(await daily(actual, new Sparebank1Impl()))
// await actual.shutdown()
registerInterrupt(bank)
try {
return await moveTransactions(actual, bank)
} finally {
await actual.shutdown()
await shutdown(bank)
}
}
async function runCronJob(bank: Bank): Promise<void> {
logger.info("Waiting for CronJob to start")
const cronJob = cronJobDaily(async () => {
let actual: Actual | undefined
try {
actual = await ActualImpl.init()
await moveTransactions(actual, bank)
} catch (exception) {
logger.error(exception, "Caught exception at CronJob, shutting down!")
await shutdown(bank, cronJob)
} finally {
await actual?.shutdown()
}
})
registerInterrupt(bank, cronJob)
}
let isShuttingDown = false
function registerInterrupt(
bank: Bank,
cronJob: CronJob | undefined = undefined,
): void {
process.on("SIGINT", async () => {
if (isShuttingDown) return
isShuttingDown = true
logger.info("Caught interrupt signal")
await shutdown(bank, cronJob)
})
}
async function shutdown(
bank: Bank,
cronJob: CronJob | undefined = undefined,
): Promise<void> {
logger.info("Shutting down, Bye!")
await bank.shutdown()
cronJob?.stop()
}
void main()

View File

@ -1,22 +0,0 @@
import type { Transaction } from "@/sparebank1.ts"
import type { TransactionEntity } from "@actual-app/api/@types/loot-core/types/models"
// TODO more fields / correct fields?
export function transactionIntoActualTransaction(
transaction: Transaction,
account: string,
): TransactionEntity {
return {
id: transaction.id,
account,
amount: transaction.amount,
date: transaction.date,
payee: transaction.description,
}
}
// TODO take the account from the bank and match it to the actual account
// Use ENV
export function bankAccountIntoActualAccount(account: string): string {
throw new Error("Not implemented")
}

View File

@ -1,67 +0,0 @@
import {
SPAREBANK1_OAUTH_CLIENT_ID,
SPAREBANK1_OAUTH_REDIRECT_URI,
SPAREBANK1_OAUTH_STATE,
} from "../config.ts"
// TODO move types
export interface OAuthTokenResponse {
access_token: string
expires_in: number
refresh_token_expires_in: number
refresh_token_absolute_expires_in: number
token_type: "Bearer"
refresh_token: string
}
export interface Transaction {
id: string
date: string
amount: number
description: string
cleanedDescription: string
remoteAccountName: string
[key: string]: string | number | boolean | unknown
}
export type Bank = Sparebank1
export interface Sparebank1 {
accessToken: () => Promise<OAuthTokenResponse>
refreshToken: (refreshToken: string) => Promise<OAuthTokenResponse>
transactionsPastDay: (
accountKeys: ReadonlyArray<string> | string,
accessToken: string,
) => Promise<ReadonlyArray<Transaction>>
}
export class Sparebank1Impl implements Sparebank1 {
private baseUrl = "https://api.sparebank1.no"
async accessToken(): Promise<OAuthTokenResponse> {
const response = await fetch(`${this.baseUrl}/oauth/authorize?
client_id=${SPAREBANK1_OAUTH_CLIENT_ID}&
state=${SPAREBANK1_OAUTH_STATE}&
redirect_uri=${SPAREBANK1_OAUTH_REDIRECT_URI}&
finInst=fid-smn&
response_type=code`)
if (response.ok) {
return await response.json()
}
throw new Error(`Failed to get access token. ${response.statusText}`)
}
async refreshToken(refreshToken: string): Promise<OAuthTokenResponse> {
throw new Error("Not implemented")
}
async transactionsPastDay(
accountKeys: ReadonlyArray<string> | string,
accessToken: string,
): Promise<ReadonlyArray<Transaction>> {
throw new Error("Not implemented")
}
}

16
tests/main.test.ts Normal file
View File

@ -0,0 +1,16 @@
import { describe, it } from "@jest/globals"
import { moveTransactions } from "@/main.ts"
import { ActualImpl } from "@/actual.ts"
import { BankStub } from "./stubs/bankStub.ts"
// TODO testcontainers with Actual?
// TODO tests don't stop after completing
describe("Main logic of the application", () => {
it("should import the transactions to Actual Budget", async () => {
const actual = await ActualImpl.init()
await moveTransactions(actual, new BankStub())
await actual.shutdown()
})
})

41
tests/stubs/bankStub.ts Normal file
View File

@ -0,0 +1,41 @@
import type { Bank, Interval } from "@/bank/sparebank1.ts"
import dayjs from "dayjs"
import type { ActualTransaction } from "@/actual.ts"
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
import type { BookingStatus, SB1Transaction } from "@sb1/types.ts"
export class BankStub implements Bank {
async fetchTransactions(
_interval: Interval,
_accountIds: ReadonlyArray<string> | string,
): Promise<ReadonlyArray<ActualTransaction>> {
const someFields = {
date: dayjs("2019-08-20").unix(),
cleanedDescription: "Test transaction",
remoteAccountName: "Test account",
bookingStatus: "BOOKED" as BookingStatus,
accountKey: "1",
}
const bankTransactions: ReadonlyArray<SB1Transaction> = [
{
id: "1",
nonUniqueId: "1",
amount: 100,
...someFields,
},
{
id: "2",
nonUniqueId: "2",
amount: 200,
...someFields,
},
{
id: "3",
nonUniqueId: "3",
amount: -50,
...someFields,
},
]
return bankTransactions.map(bankTransactionIntoActualTransaction)
}
}

View File

@ -1,4 +1,5 @@
{
"include": ["./src/**/*.ts", "./packages/**/*.ts", "./tests/**/*.ts"],
"compilerOptions": {
"target": "esnext",
"module": "ESNext",
@ -8,11 +9,13 @@
"strict": true,
"skipLibCheck": true,
"allowImportingTsExtensions": true,
"verbatimModuleSyntax": true,
"noEmit": true,
"paths": {
"@/*": [
"./src/*"
]
"@/*": ["./src/*"],
"@common/*": ["./packages/common/*"],
"@sb1/*": ["./packages/sparebank1Api/*"],
"@sb1impl/*": ["./packages/sparebank1/*"]
}
}
},
"exclude": ["node_modules", "./*.ts", "__test__"]
}