🧹 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
This commit is contained in:
@ -7,7 +7,7 @@ import {
|
||||
} from "../config.ts"
|
||||
import type { TransactionEntity } from "@actual-app/api/@types/loot-core/types/models"
|
||||
import { type UUID } from "node:crypto"
|
||||
import logger from "@/logger.ts"
|
||||
import logger from "@common/logger.ts"
|
||||
|
||||
export interface Actual {
|
||||
importTransactions: (
|
||||
|
@ -1,7 +1,7 @@
|
||||
import Database from "better-sqlite3"
|
||||
|
||||
import { type OAuthTokenResponse } from "@/bank/sparebank1.ts"
|
||||
import dayjs, { type Dayjs } from "dayjs"
|
||||
import type { OAuthTokenResponse } from "@sb1/types.ts"
|
||||
|
||||
export type TokenResponse = {
|
||||
key: TokenKey
|
||||
@ -9,10 +9,8 @@ export type TokenResponse = {
|
||||
expires_at: Dayjs
|
||||
}
|
||||
|
||||
export type TokenResponseRaw = {
|
||||
key: TokenResponse["key"]
|
||||
token: TokenResponse["token"]
|
||||
expires_at: string
|
||||
type TokenResponseRaw = {
|
||||
[K in keyof TokenResponse]: K extends "expires_at" ? string : TokenResponse[K]
|
||||
}
|
||||
|
||||
export type TokenKey = "access-token" | "refresh-token"
|
||||
|
@ -1,47 +1,22 @@
|
||||
import { BANK_INITIAL_REFRESH_TOKEN } from "@/../config.ts"
|
||||
import logger from "@/logger.ts"
|
||||
import dayjs, { Dayjs } from "dayjs"
|
||||
import { Database } from "better-sqlite3"
|
||||
import {
|
||||
BANK_INITIAL_REFRESH_TOKEN,
|
||||
BANK_OAUTH_CLIENT_ID,
|
||||
BANK_OAUTH_CLIENT_SECRET,
|
||||
} from "@/../config.ts"
|
||||
import logger from "@common/logger.ts"
|
||||
import dayjs, { type Dayjs } from "dayjs"
|
||||
import type { Database } from "better-sqlite3"
|
||||
import {
|
||||
clearTokens,
|
||||
fetchToken,
|
||||
insertTokens,
|
||||
type TokenResponse,
|
||||
} from "@/bank/db/queries.ts"
|
||||
import * as Api from "./sparebank1Api.ts"
|
||||
import { ActualTransaction } from "@/actual.ts"
|
||||
import * as Oauth from "@sb1/oauth.ts"
|
||||
import * as Transactions from "@sb1/transactions.ts"
|
||||
import type { ActualTransaction } from "@/actual.ts"
|
||||
import { bankTransactionIntoActualTransaction } from "@/mappings.ts"
|
||||
|
||||
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"
|
||||
|
||||
export interface Transaction {
|
||||
id: string
|
||||
nonUniqueId: string
|
||||
// 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<Transaction>
|
||||
}
|
||||
import type { OAuthTokenResponse } from "@sb1/types.ts"
|
||||
|
||||
export interface Bank {
|
||||
fetchTransactions: (
|
||||
@ -66,7 +41,7 @@ export class Sparebank1Impl implements Bank {
|
||||
interval: Interval,
|
||||
...accountKeys: ReadonlyArray<string>
|
||||
): Promise<ReadonlyArray<ActualTransaction>> {
|
||||
const response = await Api.transactions(
|
||||
const response = await Transactions.list(
|
||||
await this.getAccessToken(),
|
||||
accountKeys,
|
||||
interval,
|
||||
@ -105,7 +80,11 @@ export class Sparebank1Impl implements Bank {
|
||||
|
||||
private async fetchNewTokens(): Promise<OAuthTokenResponse> {
|
||||
const refreshToken = await this.getRefreshToken()
|
||||
const result = await Api.refreshToken(refreshToken)
|
||||
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}'`)
|
||||
|
@ -1,72 +0,0 @@
|
||||
import { BANK_OAUTH_CLIENT_ID, BANK_OAUTH_CLIENT_SECRET } from "@/../config.ts"
|
||||
import type {
|
||||
Interval,
|
||||
OAuthTokenResponse,
|
||||
TransactionResponse,
|
||||
} from "@/bank/sparebank1.ts"
|
||||
import logger from "@/logger.ts"
|
||||
import { toISODateString } from "@/date.ts"
|
||||
import * as querystring from "node:querystring"
|
||||
|
||||
const baseUrl = "https://api.sparebank1.no"
|
||||
|
||||
type Success<T> = { status: "success"; data: T }
|
||||
type Failure<T> = { status: "failure"; data: T }
|
||||
type Result<OK, Err> = Success<OK> | Failure<Err>
|
||||
|
||||
const success = <T>(data: T): Success<T> => ({ status: "success", data: data })
|
||||
const failure = <T>(data: T): Failure<T> => ({ status: "failure", data: data })
|
||||
|
||||
export async function transactions(
|
||||
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.debug(`Sending GET request to '${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: [] }
|
||||
}
|
||||
}
|
||||
|
||||
export async function refreshToken(
|
||||
refreshToken: string,
|
||||
): Promise<Result<OAuthTokenResponse, string>> {
|
||||
const queries = querystring.stringify({
|
||||
client_id: BANK_OAUTH_CLIENT_ID,
|
||||
client_secret: BANK_OAUTH_CLIENT_SECRET,
|
||||
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())
|
||||
}
|
@ -1,5 +1,5 @@
|
||||
import { CronJob } from "cron"
|
||||
import logger from "@/logger.ts"
|
||||
import logger from "@common/logger.ts"
|
||||
|
||||
/**
|
||||
* Run a function every day at 1 AM, Oslo time.
|
||||
|
@ -1,3 +0,0 @@
|
||||
import { type Dayjs } from "dayjs"
|
||||
|
||||
export const toISODateString = (day: Dayjs): string => day.format("YYYY-MM-DD")
|
@ -1,5 +1,5 @@
|
||||
import * as fs from "node:fs"
|
||||
import logger from "./logger"
|
||||
import logger from "@common/logger"
|
||||
|
||||
export function createDirsIfMissing(...directories: string[]): void {
|
||||
directories.forEach(createDirIfMissing)
|
||||
|
@ -1,17 +0,0 @@
|
||||
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 {
|
||||
logger.info(args, args?.[0])
|
||||
}
|
||||
|
||||
export default logger
|
@ -9,7 +9,7 @@ import {
|
||||
TRANSACTION_RELATIVE_FROM_DATE,
|
||||
TRANSACTION_RELATIVE_TO_DATE,
|
||||
} from "../config.ts"
|
||||
import logger from "@/logger.ts"
|
||||
import logger from "@common/logger.ts"
|
||||
import type { UUID } from "node:crypto"
|
||||
import { createDb } from "@/bank/db/queries.ts"
|
||||
import { CronJob } from "cron"
|
||||
|
@ -1,13 +1,13 @@
|
||||
import type { Transaction } from "@/bank/sparebank1.ts"
|
||||
import type { UUID } from "node:crypto"
|
||||
import dayjs from "dayjs"
|
||||
import { toISODateString } from "@/date.ts"
|
||||
import { type ActualTransaction } from "@/actual.ts"
|
||||
import { ACTUAL_ACCOUNT_IDS, BANK_ACCOUNT_IDS } from "../config.ts"
|
||||
import logger from "@/logger.ts"
|
||||
import logger from "@common/logger.ts"
|
||||
import { toISODateString } from "@common/date.ts"
|
||||
import type { SB1Transaction } from "@sb1/types.ts"
|
||||
|
||||
export function bankTransactionIntoActualTransaction(
|
||||
transaction: Transaction,
|
||||
transaction: SB1Transaction,
|
||||
): ActualTransaction {
|
||||
return {
|
||||
id: transaction.id,
|
||||
@ -23,12 +23,12 @@ export function bankTransactionIntoActualTransaction(
|
||||
}
|
||||
}
|
||||
|
||||
export function isCleared(transaction: Transaction): boolean {
|
||||
export function isCleared(transaction: SB1Transaction): boolean {
|
||||
const id = Number(transaction.nonUniqueId)
|
||||
return transaction.bookingStatus === "BOOKED" && !Number.isNaN(id) && id > 0
|
||||
}
|
||||
|
||||
function getActualAccountId(transcation: Transaction): UUID {
|
||||
function getActualAccountId(transcation: SB1Transaction): UUID {
|
||||
for (
|
||||
let i = 0;
|
||||
i < Math.min(ACTUAL_ACCOUNT_IDS.length, BANK_ACCOUNT_IDS.length);
|
||||
|
Reference in New Issue
Block a user