2024-11-17 22:27:29 +01:00
|
|
|
// TODO move types
|
2024-12-26 14:08:09 +01:00
|
|
|
import { BANK_INITIAL_REFRESH_TOKEN } from "@/../config.ts"
|
2024-12-25 21:06:42 +01:00
|
|
|
import logger from "@/logger.ts"
|
|
|
|
import dayjs from "dayjs"
|
2024-12-26 14:08:09 +01:00
|
|
|
import { Database } from "better-sqlite3"
|
2025-01-25 18:01:47 +01:00
|
|
|
import {
|
|
|
|
fetchToken,
|
|
|
|
insertTokens,
|
|
|
|
type TokenResponse,
|
|
|
|
} from "@/bank/db/queries.ts"
|
2024-12-26 14:08:09 +01:00
|
|
|
import * as Api from "./sparebank1Api.ts"
|
2025-01-25 18:01:47 +01:00
|
|
|
import { toISODateString } from "@/date.ts"
|
2024-12-25 21:06:42 +01:00
|
|
|
|
2024-11-17 22:27:29 +01:00
|
|
|
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
|
2025-01-25 18:01:47 +01:00
|
|
|
nonUniqueId: string
|
|
|
|
date: number // Unix time
|
|
|
|
amount: number // Amount in NOK
|
2024-11-17 22:27:29 +01:00
|
|
|
cleanedDescription: string
|
|
|
|
remoteAccountName: string
|
|
|
|
|
|
|
|
[key: string]: string | number | boolean | unknown
|
|
|
|
}
|
|
|
|
|
2025-01-25 18:01:47 +01:00
|
|
|
export interface TransactionResponse {
|
|
|
|
transactions: ReadonlyArray<Transaction>
|
|
|
|
}
|
|
|
|
|
2024-11-17 22:27:29 +01:00
|
|
|
export type Bank = Sparebank1
|
|
|
|
|
|
|
|
export interface Sparebank1 {
|
|
|
|
transactionsPastDay: (
|
|
|
|
accountKeys: ReadonlyArray<string> | string,
|
2025-01-25 18:01:47 +01:00
|
|
|
) => Promise<TransactionResponse>
|
2024-11-17 22:27:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
export class Sparebank1Impl implements Sparebank1 {
|
2024-12-25 21:06:42 +01:00
|
|
|
private static baseUrl = "https://api.sparebank1.no"
|
2024-12-26 14:08:09 +01:00
|
|
|
private readonly db: Database
|
|
|
|
|
|
|
|
constructor(db: Database) {
|
|
|
|
this.db = db
|
|
|
|
}
|
2024-11-17 22:27:29 +01:00
|
|
|
|
2025-01-22 21:00:04 +01:00
|
|
|
private async getAccessToken(): Promise<string> {
|
|
|
|
const accessToken = fetchToken(this.db, "access-token")
|
2024-11-17 22:27:29 +01:00
|
|
|
|
2025-01-22 21:00:04 +01:00
|
|
|
if (accessToken && this.isValidToken(accessToken)) {
|
|
|
|
return accessToken.token
|
|
|
|
}
|
|
|
|
const response = await this.fetchNewTokens()
|
|
|
|
return response.access_token
|
2024-11-17 22:27:29 +01:00
|
|
|
}
|
|
|
|
|
2025-01-22 21:00:04 +01:00
|
|
|
private isValidToken(tokenResponse: TokenResponse): boolean {
|
2025-01-25 18:01:47 +01:00
|
|
|
// TODO make sure the same timezone is used. Db uses UTC
|
|
|
|
return dayjs().isBefore(tokenResponse.expires_at)
|
2024-12-25 21:06:42 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
private async getRefreshToken(): Promise<string> {
|
2025-01-22 21:00:04 +01:00
|
|
|
const tokenResponse = fetchToken(this.db, "refresh-token")
|
2025-01-25 18:01:47 +01:00
|
|
|
logger.debug(`Database returned refresh token: '%o'`, tokenResponse)
|
2025-01-22 21:00:04 +01:00
|
|
|
if (!tokenResponse) {
|
2024-12-25 21:06:42 +01:00
|
|
|
return BANK_INITIAL_REFRESH_TOKEN
|
2025-01-22 21:00:04 +01:00
|
|
|
} else if (this.isValidToken(tokenResponse)) {
|
|
|
|
return tokenResponse.token
|
2024-12-25 21:06:42 +01:00
|
|
|
}
|
2025-01-22 21:00:04 +01:00
|
|
|
// TODO clear database, if refresh token is invalid, will cause Exceptions on each call
|
|
|
|
throw new Error("Refresh token is expired. Create a new one")
|
2024-12-25 21:06:42 +01:00
|
|
|
}
|
|
|
|
|
2025-01-22 21:00:04 +01:00
|
|
|
async fetchNewTokens(): Promise<OAuthTokenResponse> {
|
|
|
|
const refreshToken = await this.getRefreshToken()
|
2025-01-25 18:01:47 +01:00
|
|
|
logger.debug(`Found refresh token '${refreshToken}'`)
|
2024-12-26 14:08:09 +01:00
|
|
|
const result = await Api.refreshToken(refreshToken)
|
|
|
|
|
|
|
|
if (result.status === "failure") {
|
2025-01-25 18:01:47 +01:00
|
|
|
throw logger.error({
|
|
|
|
err: new Error(`Failed to fetch refresh token: '${result.data}'`),
|
|
|
|
})
|
2024-12-25 21:06:42 +01:00
|
|
|
}
|
2024-12-26 14:08:09 +01:00
|
|
|
const oAuthToken = result.data
|
|
|
|
|
|
|
|
insertTokens(this.db, oAuthToken)
|
2024-12-25 21:06:42 +01:00
|
|
|
return oAuthToken
|
2024-11-17 22:27:29 +01:00
|
|
|
}
|
|
|
|
|
|
|
|
async transactionsPastDay(
|
|
|
|
accountKeys: ReadonlyArray<string> | string,
|
2025-01-25 18:01:47 +01:00
|
|
|
): Promise<TransactionResponse> {
|
2024-12-25 21:06:42 +01:00
|
|
|
const today = dayjs()
|
|
|
|
const lastDay = today.subtract(1, "day")
|
2025-01-25 18:01:47 +01:00
|
|
|
|
2024-12-25 21:06:42 +01:00
|
|
|
const queries = new URLSearchParams({
|
|
|
|
// TODO allow multiple accountKeys
|
|
|
|
accountKey:
|
|
|
|
typeof accountKeys === "string" ? accountKeys : accountKeys[0],
|
2025-01-25 18:01:47 +01:00
|
|
|
fromDate: toISODateString(lastDay),
|
|
|
|
toDate: toISODateString(today),
|
2024-12-25 21:06:42 +01:00
|
|
|
})
|
|
|
|
|
|
|
|
const accessToken = await this.getAccessToken()
|
2025-01-25 18:01:47 +01:00
|
|
|
logger.debug(`Found access token '${accessToken}'`)
|
|
|
|
const url = `${Sparebank1Impl.baseUrl}/personal/banking/transactions?${queries}`
|
|
|
|
logger.debug(`Sending GET request to '${url}'`)
|
|
|
|
const response = await fetch(url, {
|
|
|
|
headers: {
|
|
|
|
Authorization: `Bearer ${accessToken}`,
|
|
|
|
Accept: "application/vnd.sparebank1.v1+json;charset=utf-8",
|
2024-12-25 21:06:42 +01:00
|
|
|
},
|
2025-01-25 18:01:47 +01:00
|
|
|
})
|
|
|
|
logger.debug(`Received response with status '${response.status}'`)
|
2024-12-25 21:06:42 +01:00
|
|
|
if (response.ok) {
|
|
|
|
return response.json()
|
|
|
|
} else {
|
2025-01-25 18:01:47 +01:00
|
|
|
logger.warn(await response.json())
|
|
|
|
return { transactions: [] }
|
2024-12-25 21:06:42 +01:00
|
|
|
}
|
2024-11-17 22:27:29 +01:00
|
|
|
}
|
2024-11-15 22:55:53 +01:00
|
|
|
}
|