chiakeo 0.1.0 → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/chiakeo.mjs +56 -51
  2. package/package.json +1 -1
package/chiakeo.mjs CHANGED
@@ -16,21 +16,21 @@ const CONFIG_FILE_MODE = 0o600;
16
16
  const AMOUNT_UNITS = { k: 1_000, m: 1_000_000 };
17
17
  const AMOUNT_PATTERN = /^(\d+(?:[.,]\d+)?)([km])?$/i;
18
18
 
19
- const HELP = `chiakeo: dòng lệnh cho Chia Kèo
19
+ const HELP = `chiakeo: command line for Chia Kèo
20
20
 
21
- up [--url URL] [--name TÊN] đăng nhập bằng mã (như tailscale up)
22
- down xóa token trên máy này
23
- whoami xem đang đăng nhập là ai
24
- games danh sách kèo đang chơi
25
- game <kèo> chi tiết, số dư và ai chuyển cho ai
26
- new <tên> [--people N] tạo kèo mới
27
- add-person <kèo> <tên...> thêm người
28
- add-expense <kèo> <nội dung> <số tiền> --payer TÊN [--split A,B] [--note GHI CHÚ]
29
- pay <kèo> <người trả> <người nhận> <số tiền>
30
- api <METHOD> <đường dẫn> [json] gọi thẳng REST API
21
+ up [--url URL] [--name NAME] sign in with a code (like tailscale up)
22
+ down delete the token on this computer
23
+ whoami show who is signed in
24
+ games list the open games
25
+ game <game> details, balances and who pays whom
26
+ new <name> [--people N] create a game
27
+ add-person <game> <name...> add people
28
+ add-expense <game> <title> <amount> --payer NAME [--split A,B] [--note NOTE]
29
+ pay <game> <from> <to> <amount>
30
+ api <METHOD> <path> [json] call the REST API directly
31
31
 
32
- <kèo> là mã, id hoặc tên kèo. Số tiền: 50000, 50k, 1.5m.
33
- Biến môi trường: CHIAKEO_CONFIG (đường dẫn file cấu hình).`;
32
+ <game> is the game code, id or name. Amount: 50000, 50k, 1.5m.
33
+ Environment: CHIAKEO_CONFIG (path of the config file).`;
34
34
 
35
35
  class CliError extends Error {}
36
36
 
@@ -45,7 +45,7 @@ function parseArgs(argv) {
45
45
  }
46
46
  const value = argv[index + 1];
47
47
  if (value === undefined || value.startsWith("--")) {
48
- throw new CliError(`Thiếu giá trị cho ${arg}`);
48
+ throw new CliError(`Missing value for ${arg}`);
49
49
  }
50
50
  flags[arg.slice(2)] = value;
51
51
  index += 1;
@@ -55,10 +55,10 @@ function parseArgs(argv) {
55
55
 
56
56
  function parseAmount(raw) {
57
57
  const match = AMOUNT_PATTERN.exec(String(raw ?? "").trim());
58
- if (!match) throw new CliError(`Số tiền không hợp lệ: ${raw}`);
58
+ if (!match) throw new CliError(`Bad amount: ${raw}`);
59
59
  const unit = AMOUNT_UNITS[(match[2] || "").toLowerCase()] ?? 1;
60
60
  const amount = Math.round(Number(match[1].replace(",", ".")) * unit);
61
- if (amount <= 0) throw new CliError(`Số tiền phải lớn hơn 0: ${raw}`);
61
+ if (amount <= 0) throw new CliError(`Amount must be more than 0: ${raw}`);
62
62
  return amount;
63
63
  }
64
64
 
@@ -68,7 +68,7 @@ async function readConfig() {
68
68
  try {
69
69
  return JSON.parse(await readFile(CONFIG_PATH, "utf8"));
70
70
  } catch {
71
- throw new CliError("Chưa đăng nhập. Chạy: chiakeo up");
71
+ throw new CliError("You are not signed in. Run: chiakeo up");
72
72
  }
73
73
  }
74
74
 
@@ -83,7 +83,7 @@ async function request(baseUrl, method, path, body, token) {
83
83
  });
84
84
  const data = await response.json().catch(() => ({}));
85
85
  if (!response.ok) {
86
- throw new CliError(`${response.status} ${data.error || "lỗi không rõ"}`);
86
+ throw new CliError(`${response.status} ${data.error || "unknown error"}`);
87
87
  }
88
88
  return data;
89
89
  }
@@ -102,10 +102,10 @@ async function up({ flags }) {
102
102
  name: (flags.name || hostname()).slice(0, DEVICE_NAME_MAX_LENGTH),
103
103
  });
104
104
 
105
- console.log(`Mở link này trong trình duyệt (đăng nhập nếu được hỏi):
105
+ console.log(`Open this link in your browser (sign in if asked):
106
106
  ${start.verificationUrl}?code=${start.userCode}
107
- Hoặc mở ${start.verificationUrl} và nhập mã: ${start.userCode}
108
- Đang chờ duyệt...`);
107
+ Or open ${start.verificationUrl} and type this code: ${start.userCode}
108
+ Waiting for approval...`);
109
109
 
110
110
  const deadline = Date.now() + start.expiresInSeconds * 1000;
111
111
  while (Date.now() < deadline) {
@@ -119,29 +119,30 @@ Hoặc mở ${start.verificationUrl} và nhập mã: ${start.userCode}
119
119
  mode: CONFIG_FILE_MODE,
120
120
  });
121
121
  await chmod(CONFIG_PATH, CONFIG_FILE_MODE);
122
- console.log("Đã đăng nhập.");
122
+ console.log("Signed in.");
123
123
  return;
124
124
  }
125
125
  if (status === "expired") break;
126
126
  }
127
- throw new CliError("Mã hết hạn. Chạy lại: chiakeo up");
127
+ throw new CliError("The code has expired. Run again: chiakeo up");
128
128
  }
129
129
 
130
130
  async function down() {
131
131
  await rm(CONFIG_PATH, { force: true });
132
132
  console.log(
133
- "Đã xóa token trên máy này. Muốn thu hồi hẳn thì vào Cài đặt > Token trên web.",
133
+ "Deleted the token on this computer. To revoke it fully, open Settings > Tokens on the website.",
134
134
  );
135
135
  }
136
136
 
137
137
  async function whoami() {
138
138
  const { user } = await authed("GET", "/api/session");
139
- if (!user) throw new CliError("Token không còn hiệu lực. Chạy: chiakeo up");
139
+ if (!user)
140
+ throw new CliError("The token is no longer valid. Run: chiakeo up");
140
141
  console.log(user.name);
141
142
  }
142
143
 
143
144
  async function findGame(ref) {
144
- // Kèo tất toán xong tự đóng và rời danh sách đang chơi, nên tìm cả kèo đã đóng.
145
+ // A settled game closes by itself and leaves the open list, so search closed games too.
145
146
  const [active, closed] = await Promise.all([
146
147
  authed("GET", "/api/games"),
147
148
  authed("GET", "/api/games/closed"),
@@ -156,8 +157,8 @@ async function findGame(ref) {
156
157
  if (matches.length !== 1) {
157
158
  throw new CliError(
158
159
  matches.length === 0
159
- ? `Không thấy kèo "${ref}" `
160
- : `Có ${matches.length} kèo khớp "${ref}", dùng mã kèo`,
160
+ ? `No game found for "${ref}"`
161
+ : `${matches.length} games match "${ref}", use the game code`,
161
162
  );
162
163
  }
163
164
  return matches[0];
@@ -174,7 +175,7 @@ function findPerson(game, name) {
174
175
  );
175
176
  if (!person) {
176
177
  const names = game.participants.map((item) => item.name).join(", ");
177
- throw new CliError(`Không thấy "${name}" trong kèo. Có: ${names}`);
178
+ throw new CliError(`No person "${name}" in this game. People: ${names}`);
178
179
  }
179
180
  return person;
180
181
  }
@@ -183,75 +184,75 @@ async function games() {
183
184
  const list = await authed("GET", "/api/games");
184
185
  for (const game of list) {
185
186
  console.log(
186
- `${game.code} ${game.name} (${game.participantCount} người, ${game.expenseCount} khoản)`,
187
+ `${game.code} ${game.name} (${game.participantCount} people, ${game.expenseCount} expenses)`,
187
188
  );
188
189
  }
189
- if (list.length === 0) console.log("Chưa có kèo nào đang chơi.");
190
+ if (list.length === 0) console.log("No open games.");
190
191
  }
191
192
 
192
193
  async function game({ positional }) {
193
- const detail = await loadGame(requireArg(positional[1], "<kèo>"));
194
+ const detail = await loadGame(requireArg(positional[1], "<game>"));
194
195
  const nameOf = (id) =>
195
196
  detail.participants.find((item) => item.id === id)?.name ?? id;
196
197
  console.log(`${detail.name} (${detail.code})`);
197
- console.log(`Tổng chi: ${money(detail.summary.totalExpense)}`);
198
+ console.log(`Total spent: ${money(detail.summary.totalExpense)}`);
198
199
  for (const row of detail.summary.balances) {
199
200
  console.log(
200
- ` ${nameOf(row.participantId)}: trả ${money(row.paid)}, phải chịu ${money(row.owed)}, số dư ${money(row.balance)}`,
201
+ ` ${nameOf(row.participantId)}: paid ${money(row.paid)}, owes ${money(row.owed)}, balance ${money(row.balance)}`,
201
202
  );
202
203
  }
203
204
  for (const row of detail.summary.settlements) {
204
205
  console.log(
205
- `${nameOf(row.fromParticipantId)} chuyển ${money(row.amount)} cho ${nameOf(row.toParticipantId)}`,
206
+ `${nameOf(row.fromParticipantId)} sends ${money(row.amount)} to ${nameOf(row.toParticipantId)}`,
206
207
  );
207
208
  }
208
209
  }
209
210
 
210
211
  async function newGame({ positional, flags }) {
211
212
  const created = await authed("POST", "/api/games", {
212
- name: requireArg(positional[1], "<tên>"),
213
+ name: requireArg(positional[1], "<name>"),
213
214
  participantCount: Number(flags.people || 0),
214
215
  });
215
- console.log(`Đã tạo kèo ${created.name} (${created.code})`);
216
+ console.log(`Created game ${created.name} (${created.code})`);
216
217
  }
217
218
 
218
219
  async function addPerson({ positional }) {
219
- const target = await findGame(requireArg(positional[1], "<kèo>"));
220
+ const target = await findGame(requireArg(positional[1], "<game>"));
220
221
  const names = positional.slice(2);
221
- if (names.length === 0) throw new CliError("Thiếu <tên...>");
222
+ if (names.length === 0) throw new CliError("Missing <name...>");
222
223
  for (const name of names) {
223
224
  await authed("POST", `/api/games/${target.id}/participants`, { name });
224
225
  }
225
- console.log(`Đã thêm ${names.join(", ")} vào ${target.name}`);
226
+ console.log(`Added ${names.join(", ")} to ${target.name}`);
226
227
  }
227
228
 
228
229
  async function addExpense({ positional, flags }) {
229
- const detail = await loadGame(requireArg(positional[1], "<kèo>"));
230
+ const detail = await loadGame(requireArg(positional[1], "<game>"));
230
231
  const payer = findPerson(detail, requireArg(flags.payer, "--payer"));
231
232
  const split = flags.split
232
233
  ? flags.split.split(",").map((name) => findPerson(detail, name.trim()))
233
234
  : detail.participants;
234
235
  await authed("POST", `/api/games/${detail.id}/expenses`, {
235
- title: requireArg(positional[2], "<nội dung>"),
236
+ title: requireArg(positional[2], "<title>"),
236
237
  amount: parseAmount(positional[3]),
237
238
  note: flags.note || "",
238
239
  payerParticipantId: payer.id,
239
240
  splitMode: "equal",
240
241
  splitParticipantIds: split.map((person) => person.id),
241
242
  });
242
- console.log(`Đã thêm khoản chi ${positional[2]} vào ${detail.name}`);
243
+ console.log(`Added expense ${positional[2]} to ${detail.name}`);
243
244
  }
244
245
 
245
246
  async function pay({ positional }) {
246
- const detail = await loadGame(requireArg(positional[1], "<kèo>"));
247
- const from = findPerson(detail, requireArg(positional[2], "<người trả>"));
248
- const to = findPerson(detail, requireArg(positional[3], "<người nhận>"));
247
+ const detail = await loadGame(requireArg(positional[1], "<game>"));
248
+ const from = findPerson(detail, requireArg(positional[2], "<from>"));
249
+ const to = findPerson(detail, requireArg(positional[3], "<to>"));
249
250
  await authed("POST", `/api/games/${detail.id}/transfers`, {
250
251
  fromParticipantId: from.id,
251
252
  toParticipantId: to.id,
252
253
  amount: parseAmount(positional[4]),
253
254
  });
254
- console.log(`Đã ghi nhận ${from.name} trả ${to.name}`);
255
+ console.log(`Recorded: ${from.name} paid ${to.name}`);
255
256
  }
256
257
 
257
258
  async function api({ positional }) {
@@ -259,14 +260,14 @@ async function api({ positional }) {
259
260
  const body = json === undefined ? undefined : JSON.parse(json);
260
261
  const data = await authed(
261
262
  requireArg(method, "<METHOD>").toUpperCase(),
262
- requireArg(path, "<đường dẫn>"),
263
+ requireArg(path, "<path>"),
263
264
  body,
264
265
  );
265
266
  console.log(JSON.stringify(data, null, 2));
266
267
  }
267
268
 
268
269
  function requireArg(value, label) {
269
- if (value === undefined) throw new CliError(`Thiếu ${label}`);
270
+ if (value === undefined) throw new CliError(`Missing ${label}`);
270
271
  return value;
271
272
  }
272
273
 
@@ -286,11 +287,15 @@ const COMMANDS = {
286
287
 
287
288
  async function main() {
288
289
  const args = parseArgs(process.argv.slice(2));
289
- const command = COMMANDS[args.positional[0]];
290
- if (!command) {
290
+ const [name] = args.positional;
291
+ if (name === undefined) {
291
292
  console.log(HELP);
292
293
  return;
293
294
  }
295
+ const command = COMMANDS[name];
296
+ if (!command) {
297
+ throw new CliError(`Unknown command: ${name}. Run chiakeo for help.`);
298
+ }
294
299
  await command(args);
295
300
  }
296
301
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "chiakeo",
3
- "version": "0.1.0",
3
+ "version": "0.1.1",
4
4
  "description": "Command line for Chia Kèo: log in with a device code, read and write games",
5
5
  "type": "module",
6
6
  "bin": {