aboutsummaryrefslogtreecommitdiffstats
path: root/cli/src/commands/accounts.ts
blob: 4b7e980b4630b13f304c1c4ea4158fc387217092 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import * as p from "@clack/prompts"
import { loadConfig, saveConfig } from "../config"
import { createSb1Client } from "../sb1"
import { getAccounts } from "../actual"

export async function accounts() {
    const config = loadConfig()
    const sb1 = createSb1Client(config.sb1)

    const spinner = p.spinner()
    spinner.start("Fetching accounts...")
    const [sb1Accounts, actualAccounts] = await Promise.all([
        sb1.getAccounts(),
        getAccounts(config.actual)
    ])
    spinner.stop("Accounts loaded.")

    const openActualAccounts = actualAccounts.filter(a => !a.closed)

    p.intro("Account mappings")

    const mappings = []
    for (const sb1Account of sb1Accounts) {
        const existing = config.mappings.find(m => m.sb1Id === sb1Account.key)

        const actualId = await p.select({
            message: `${sb1Account.name} (${sb1Account.balance} ${sb1Account.currencyCode})`,
            options: [
                { value: null, label: "Skip" },
                ...openActualAccounts.map(a => ({ value: a.id, label: a.name }))
            ],
            initialValue: existing?.actualId ?? null,
        })

        if (p.isCancel(actualId)) {
            p.cancel("Cancelled.")
            process.exit(0)
        }

        if (actualId) mappings.push({ sb1Id: sb1Account.key, actualId, label: sb1Account.name })
    }

    saveConfig({ ...config, mappings })

    p.outro(`Saved ${mappings.length} mapping(s).`)
}