-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcli-helpers.ts
176 lines (162 loc) · 5.14 KB
/
cli-helpers.ts
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
import type {
CashCtrlAccount,
CashCtrlAccountCategory,
DateRange,
SpreadsheetTable,
} from "./types.ts";
import inquirer from "npm:inquirer";
import { CashCtrlApi } from "./api-cash-ctrl.ts";
import { checkbox, search, select } from "npm:@inquirer/prompts";
export class CliHelpers {
public static async selectMonth(): Promise<DateRange> {
const answers = await inquirer.prompt([
{
type: "input",
name: "startDate",
message: "Enter the start date (YYYY-MM-DD):",
default: "2025-01-01",
},
{
type: "input",
name: "endDate",
message: "Enter the end date (YYYY-MM-DD):",
default: (new Date()).toISOString().split("T")[0],
},
]);
return {
startDate: new Date(answers.startDate),
endDate: new Date(answers.endDate),
};
}
public static async selectClients(
sheetData: SpreadsheetTable,
): Promise<string[]> {
const uniqueClients = [...new Set(sheetData.map((row) => row.client))];
// todo match this client with cashCtrl client?
return await checkbox(
{
message: "Select clients",
pageSize: 20,
choices: uniqueClients.map((client) => ({
name: client,
value: client,
checked: true,
})),
validate: function (choices) {
if (choices.length < 1) {
return "You must choose at least one client.";
}
return true;
},
},
);
}
public static async selectAccount(message: string): Promise<number> {
const accounts = await CashCtrlApi.request<CashCtrlAccount>(
"/account/list.json",
);
const accountCategories = await CashCtrlApi.request<
CashCtrlAccountCategory
>(
"/account/category/list.json",
);
const accountCategoryMap: Record<number, string> = accountCategories.data
.reduce((acc, c) => {
acc[c.id] = CashCtrlApi.getTranslation(c.name);
return acc;
}, {} as Record<number, string>);
const formatAccount = (account: CashCtrlAccount): string =>
`${accountCategoryMap[account.categoryId]} | ${account.number}: ${
CashCtrlApi.getTranslation(account.name)
}`;
const defaultAccountId = Number(Deno.env.get("CASHCTRL_DEFAULT_ACCOUNT"));
const defaultAccount = accounts.data.find((a) => a.id === defaultAccountId);
if (defaultAccount) {
message += ` (default: ${formatAccount(defaultAccount)})`;
}
return search({
message: message,
source: (term: string | undefined) => {
if (!term || term.length === 0) {
if (!defaultAccount) return [];
return [{
name: formatAccount(defaultAccount),
value: defaultAccountId,
}];
}
const foundAccounts = accounts.data.filter((account) =>
account.name.toLowerCase().includes(term.toLowerCase()) ||
account.number.toLowerCase().includes(term.toLowerCase()) ||
accountCategoryMap[account.categoryId].toLowerCase().includes(
term.toLowerCase(),
)
);
return foundAccounts.map((a) => ({
name: formatAccount(a),
value: a.id,
}));
},
pageSize: 20,
});
}
public static async promptForEnvInput(
key: string,
message: string,
): Promise<string> {
if (key === "CASHCTRL_ITEMS_ORDER") {
const choicesWithLabels = [
{ value: "none", label: "No sorting" },
{ value: "date", label: "Sort by date" },
{ value: "client", label: "Sort by client name" },
{ value: "hours", label: "Sort by hours" },
{ value: "pricePerHour", label: "Sort by price per hour" },
{ value: "total", label: "Sort by total amount" },
];
const answer = await select({
message: "Select the order for items:",
choices: choicesWithLabels.map((c) => ({
name: c.label,
value: c.value,
})),
});
await CliHelpers.updateEnvFile(key, answer);
return answer;
}
if (key === "CASHCTRL_DEFAULT_ACCOUNT") {
const selectedAccount = await CliHelpers.selectAccount(
"Select default account",
);
await CliHelpers.updateEnvFile(key, selectedAccount.toString());
return selectedAccount.toString();
}
const answer = await inquirer.prompt([
{
type: "input",
name: "value",
message: message,
},
]);
const value = answer.value;
await CliHelpers.updateEnvFile(key, value);
return value;
}
public static async updateEnvFile(key: string, value: string): Promise<void> {
const envFilePath = ".env";
let envContent: string;
try {
envContent = await Deno.readTextFile(envFilePath);
} catch {
envContent = "";
}
const lines = envContent.trim().split("\n").filter(Boolean);
const keyIndex = lines.findIndex((line) => line.startsWith(`${key}=`));
if (keyIndex >= 0) {
lines[keyIndex] = `${key}=${value}`;
} else {
lines.push(`${key}=${value}`);
}
const newEnvContent = lines.join("\n");
await Deno.writeTextFile(envFilePath, newEnvContent);
Deno.env.set(key, value);
}
}