@dumbopay/cli 0.1.0 → 0.2.0

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.
package/README.md CHANGED
@@ -11,6 +11,7 @@ dumbopay inventory list --filter low
11
11
  dumbopay inventory adjust 012345678905 count 24 --note "Shelf count"
12
12
  dumbopay readout
13
13
  dumbopay accounting sales --month 2026-10 --software quickbooks --out october-sales.csv
14
+ dumbopay schedule install sales /path/to/export.csv --at 02:30 # the nightly job (the owner approves it)
14
15
  ```
15
16
 
16
17
  A key acts as the person who made it, with their permissions in the store, narrowed to the areas ticked when it was made (send files, read or change inventory, readouts and reports, alerts, the books, kiosk status). Settings, people, orders, payments and the account are never reachable with a key.
@@ -20,4 +21,8 @@ A key acts as the person who made it, with their permissions in the store, narro
20
21
  - The saved key lives in `~/.config/dumbopay/config.json`, readable by you only.
21
22
  - Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in or key refused, 4 permission denied, 5 Business Pro license needed.
22
23
 
24
+ ## The nightly job
25
+
26
+ `dumbopay schedule install <type> <file-or-folder> [--newest] [--at HH:MM] [--wait]` asks Dumbo Pay to run a nightly export from this computer. Nothing is installed until the store's owner approves the request in Business Pro → Connections → Scheduled jobs (they get a notification and an email naming the computer, the file and the time). Once approved, the command writes the scheduler entry itself: a Task Scheduler task on Windows, a launchd agent on a Mac, a crontab line on Linux. The entry runs `dumbopay schedule run <id>`; it carries no key (the key stays in the config file, readable by you only), checks the job is still approved before every run, skips a file that hasn't changed since last night, and removes itself if the owner stops the job. `schedule status`, `schedule test <id>` and `schedule remove` round it out. The key needs the owner-only "Install the nightly job" permission plus "Send files". Step by step: https://dumbopay.net/for-stores/it
27
+
23
28
  A nightly export, without the CLI, is one curl: `POST https://dumbopay.net/api/integrations/exports/sales` with `Authorization: Bearer dpx_…` and the CSV as the body.
package/bin/dumbopay.mjs CHANGED
@@ -9,16 +9,21 @@
9
9
  // dumbopay inventory list|find|set|adjust|movements|import
10
10
  // dumbopay departments [add <name>] | vendors [add <name>]
11
11
  // dumbopay readout | movement | alerts | accounting <kind> | kiosks
12
+ // dumbopay schedule install <type> <file-or-folder> [--newest] [--at HH:MM] [--wait] (the nightly job; the owner approves it)
13
+ // dumbopay schedule status | remove [id] | run <id> | test <id>
12
14
  // dumbopay api <METHOD> <path> [--data '{…}']
13
15
  //
14
16
  // Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in / key refused, 4 permission denied, 5 license.
15
17
 
16
18
  import { createInterface } from "node:readline";
17
- import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, chmodSync, statSync } from "node:fs";
18
- import { homedir } from "node:os";
19
- import { basename, join, resolve } from "node:path";
19
+ import { mkdirSync, readFileSync, writeFileSync, existsSync, unlinkSync, chmodSync, statSync, readdirSync, appendFileSync } from "node:fs";
20
+ import { homedir, hostname, userInfo, platform } from "node:os";
21
+ import { basename, join, resolve, dirname } from "node:path";
22
+ import { fileURLToPath } from "node:url";
23
+ import { createHash } from "node:crypto";
24
+ import { spawnSync } from "node:child_process";
20
25
 
21
- const VERSION = "0.1.0";
26
+ const VERSION = "0.2.0";
22
27
  const DEFAULT_API = "https://dumbopay.net";
23
28
  const CONFIG_DIR = process.env.DUMBOPAY_CONFIG_DIR || join(homedir(), ".config", "dumbopay");
24
29
  const CONFIG_FILE = join(CONFIG_DIR, "config.json");
@@ -303,6 +308,19 @@ const commands = {
303
308
  const r = await call(method, path.startsWith("/") ? path : `/${path}`, { body });
304
309
  out(typeof r === "string" ? r : JSON.stringify(r, null, 2));
305
310
  },
311
+ // -------------------------------------------------------------------------
312
+ // The nightly job. Nothing touches Task Scheduler, launchd or cron until the
313
+ // owner has approved the job in Business Pro; the entry carries no key; every
314
+ // run checks the job is still approved and removes itself when it isn't.
315
+ // -------------------------------------------------------------------------
316
+ async schedule() {
317
+ const action = sub || "status";
318
+ if (action === "install") return scheduleInstall();
319
+ if (action === "status") return scheduleStatus();
320
+ if (action === "remove") return scheduleRemove(rest[0]);
321
+ if (action === "run" || action === "test") return scheduleRun(need(rest[0], "a job id (see dumbopay schedule status)"), action === "test");
322
+ fail(`Unknown: schedule ${action}. Try install, status, remove, run, test.`, 2);
323
+ },
306
324
  version() { out(VERSION); },
307
325
  help() {
308
326
  out(`dumbopay ${VERSION}: the Dumbo Pay command line for stores.
@@ -318,12 +336,157 @@ const commands = {
318
336
  dumbopay readout | movement [--period day|week|month --date YYYY-MM-DD --csv [file]] | alerts [--refresh] | alerts dismiss <id>
319
337
  dumbopay accounting <sales|rewards|bills|journal> [--month YYYY-MM --software quickbooks|xero|generic --out file]
320
338
  dumbopay kiosks
339
+ dumbopay schedule install <type> <file-or-folder> [--newest] [--at 02:30] [--wait] nightly export; the owner approves it in Business Pro
340
+ dumbopay schedule status | remove [id] | test <id>
321
341
  dumbopay api <METHOD> <path> [--data '{…}']
322
342
 
323
343
  Everywhere: --json for machine-readable output, --api <url> for staging. Keys: Business Pro → Connections → Store keys.`);
324
344
  },
325
345
  };
326
346
 
347
+ // ---------------------------------------------------------------------------
348
+ // Scheduled exports: helpers
349
+ // ---------------------------------------------------------------------------
350
+
351
+ const CLI_PATH = fileURLToPath(import.meta.url);
352
+ const SCHEDULER = process.env.DUMBOPAY_SCHEDULER || platform(); // darwin | win32 | linux | dry (tests: write the entry, touch nothing)
353
+ const OS_NAME = platform() === "darwin" ? "darwin" : platform() === "win32" ? "win32" : "linux";
354
+ const jobLog = (id) => join(CONFIG_DIR, `schedule-${id}.log`);
355
+ const logLine = (id, text) => { try { mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 }); appendFileSync(jobLog(id), `${new Date().toISOString()} ${text}\n`, { mode: 0o600 }); } catch { /* best effort */ } };
356
+ const sha256 = (buf) => createHash("sha256").update(buf).digest("hex");
357
+ const parseAt = (v) => { const m = /^(\d{1,2}):(\d{2})$/.exec(String(v || "").trim()); if (!m || Number(m[1]) > 23 || Number(m[2]) > 59) fail("--at takes a 24-hour time like 02:30 or 23:15.", 2); return { hour: Number(m[1]), minute: Number(m[2]) }; };
358
+ const runningFromNpx = () => /[\\/]_npx[\\/]/.test(CLI_PATH);
359
+ const scheduledCommand = (id) => [process.execPath, CLI_PATH, "schedule", "run", id];
360
+ const q = (s) => `"${String(s).replace(/"/g, '\\"')}"`;
361
+
362
+ /** Writes the OS scheduler entry for a job. Returns a short description of what was written. */
363
+ function installEntry(job) {
364
+ const id = job.id; const [node, cli] = scheduledCommand(id); const log = jobLog(id);
365
+ mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
366
+ if (SCHEDULER === "dry") {
367
+ writeFileSync(join(CONFIG_DIR, `scheduler-${id}.txt`), `dry: ${OS_NAME} ${job.hour}:${String(job.minute).padStart(2, "0")} ${scheduledCommand(id).join(" ")}\n`, { mode: 0o600 });
368
+ return `dry run: entry written to ${join(CONFIG_DIR, `scheduler-${id}.txt`)} (nothing scheduled)`;
369
+ }
370
+ if (SCHEDULER === "darwin") {
371
+ const dir = join(homedir(), "Library", "LaunchAgents"); mkdirSync(dir, { recursive: true });
372
+ const plist = join(dir, `net.dumbopay.export.${id}.plist`);
373
+ const esc = (t) => String(t).replace(/&/g, "&amp;").replace(/</g, "&lt;");
374
+ writeFileSync(plist, `<?xml version="1.0" encoding="UTF-8"?>
375
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
376
+ <plist version="1.0"><dict>
377
+ <key>Label</key><string>net.dumbopay.export.${id}</string>
378
+ <key>ProgramArguments</key><array>${scheduledCommand(id).map((a) => `<string>${esc(a)}</string>`).join("")}</array>
379
+ <key>StartCalendarInterval</key><dict><key>Hour</key><integer>${job.hour}</integer><key>Minute</key><integer>${job.minute}</integer></dict>
380
+ <key>StandardOutPath</key><string>${esc(log)}</string><key>StandardErrorPath</key><string>${esc(log)}</string>
381
+ <key>RunAtLoad</key><false/>
382
+ </dict></plist>
383
+ `, { mode: 0o644 });
384
+ const uid = typeof process.getuid === "function" ? process.getuid() : 501;
385
+ spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" });
386
+ const r = spawnSync("launchctl", ["bootstrap", `gui/${uid}`, plist], { encoding: "utf8" });
387
+ if (r.status !== 0) { const r2 = spawnSync("launchctl", ["load", "-w", plist], { encoding: "utf8" }); if (r2.status !== 0) fail(`launchd refused the job: ${(r.stderr || r2.stderr || "").trim()}`); }
388
+ return `launchd agent ${plist} (runs daily, even after sleep; log: ${log})`;
389
+ }
390
+ if (SCHEDULER === "win32") {
391
+ const name = `Dumbo Pay export ${id}`; const st = `${String(job.hour).padStart(2, "0")}:${String(job.minute).padStart(2, "0")}`;
392
+ const tr = `${q(node)} ${q(cli)} schedule run ${id}`;
393
+ const r = spawnSync("schtasks", ["/Create", "/F", "/SC", "DAILY", "/ST", st, "/TN", name, "/TR", tr], { encoding: "utf8" });
394
+ if (r.status !== 0) fail(`Task Scheduler refused the job: ${(r.stderr || r.stdout || "").trim()}`);
395
+ return `Task Scheduler task "${name}" at ${st} (log: ${log})`;
396
+ }
397
+ // linux and anything else: the user's crontab
398
+ const marker = `# dumbopay:${id}`;
399
+ const current = spawnSync("crontab", ["-l"], { encoding: "utf8" }); const lines = (current.status === 0 ? current.stdout : "").split("\n").filter((l) => l.trim() && !l.includes(marker));
400
+ lines.push(`${job.minute} ${job.hour} * * * ${q(node)} ${q(cli)} schedule run ${id} >> ${q(log)} 2>&1 ${marker}`);
401
+ const w = spawnSync("crontab", ["-"], { input: lines.join("\n") + "\n", encoding: "utf8" });
402
+ if (w.status !== 0) fail(`crontab refused the job: ${(w.stderr || "").trim()}`);
403
+ return `crontab entry (${job.minute} ${job.hour} * * *; log: ${log})`;
404
+ }
405
+ function removeEntry(id) {
406
+ if (SCHEDULER === "dry") { const f = join(CONFIG_DIR, `scheduler-${id}.txt`); if (existsSync(f)) unlinkSync(f); return; }
407
+ if (SCHEDULER === "darwin") {
408
+ const plist = join(homedir(), "Library", "LaunchAgents", `net.dumbopay.export.${id}.plist`); const uid = typeof process.getuid === "function" ? process.getuid() : 501;
409
+ spawnSync("launchctl", ["bootout", `gui/${uid}`, plist], { stdio: "ignore" }); if (existsSync(plist)) unlinkSync(plist); return;
410
+ }
411
+ if (SCHEDULER === "win32") { spawnSync("schtasks", ["/Delete", "/F", "/TN", `Dumbo Pay export ${id}`], { stdio: "ignore" }); return; }
412
+ const marker = `# dumbopay:${id}`; const current = spawnSync("crontab", ["-l"], { encoding: "utf8" });
413
+ if (current.status === 0) { const lines = current.stdout.split("\n").filter((l) => l.trim() && !l.includes(marker)); spawnSync("crontab", ["-"], { input: lines.join("\n") + (lines.length ? "\n" : ""), encoding: "utf8" }); }
414
+ }
415
+ const savedJobs = () => (config.schedules && typeof config.schedules === "object" ? config.schedules : {});
416
+ const saveJob = (job, extra = {}) => { const all = savedJobs(); all[job.id] = { type: job.type, path: job.path, mode: job.mode, hour: job.hour, minute: job.minute, ...(all[job.id] || {}), ...extra }; writeConfig({ ...config, schedules: all }); };
417
+ const forgetJob = (id) => { const all = savedJobs(); delete all[id]; writeConfig({ ...config, schedules: all }); };
418
+ const statusLine = (j) => `${j.status === "approved" ? (j.installedAt ? "approved, installed" : "approved, not installed yet") : j.status}`;
419
+
420
+ async function scheduleInstall() {
421
+ const type = need(rest[0], `a file type (${IMPORT_TYPES.join(", ")})`); if (!IMPORT_TYPES.includes(type)) fail(`The type is one of ${IMPORT_TYPES.join(", ")}.`, 2);
422
+ const target = resolve(need(rest[1], "the file to send, or a folder with --newest"));
423
+ const mode = flags.newest ? "newest" : "file";
424
+ if (mode === "newest" && !(existsSync(target) && statSync(target).isDirectory())) fail(`--newest needs a folder: ${target}`, 2);
425
+ if (mode === "file" && existsSync(target) && statSync(target).isDirectory()) fail(`${target} is a folder. Add --newest to send its newest .csv each night, or name the file.`, 2);
426
+ if (runningFromNpx() && !flags["allow-npx"]) fail("Install the command line first so the job survives: npm install -g @dumbopay/cli (the npx copy can be cleaned away).", 2);
427
+ const { hour, minute } = parseAt(flag("at", "02:30"));
428
+ const me = await call("GET", "/api/integrations/me");
429
+ if (!me.key) fail("Scheduled jobs need a store key sign-in (dumbopay login --key dpx_…).", 3);
430
+ if (!me.key.scopes.includes("schedule:write")) fail("This key can't install the nightly job. The owner makes a key with “Install the nightly job” ticked (Business Pro → Connections → Store keys).", 4);
431
+ const body = { type, path: target, mode, hour, minute, machine: hostname().slice(0, 80), os: OS_NAME, username: (() => { try { return userInfo().username; } catch { return ""; } })().slice(0, 80), cliVersion: VERSION };
432
+ let r = await call("POST", "/api/integrations/schedules", { body });
433
+ let job = r.job;
434
+ if (job.status === "pending") {
435
+ out(`Asked the owner to approve: ${type} from ${mode === "newest" ? "the newest file in " : ""}${target} every day at ${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")} from ${body.machine}.`);
436
+ out(`Nothing is installed until it's approved in Business Pro → Connections → Scheduled jobs (${r.approveUrl}).`);
437
+ if (!flags.wait) { saveJob(job); emit({ job, installed: false }, () => out("Run this same command again after the approval, or add --wait to keep checking for up to 15 minutes.")); return; }
438
+ const until = Date.now() + 15 * 60_000;
439
+ while (Date.now() < until && job.status === "pending") { await new Promise((ok) => setTimeout(ok, 10_000)); job = (await call("GET", `/api/integrations/schedules/${job.id}`)).job; }
440
+ }
441
+ if (job.status !== "approved") { saveJob(job); fail(job.status === "pending" ? "Still waiting for the owner's approval. Run the command again once it's approved." : `The owner ${job.status} this job; nothing was installed.`, job.status === "pending" ? 1 : 4); }
442
+ const where = installEntry(job);
443
+ await call("POST", `/api/integrations/schedules/${job.id}/installed`, { body: {} });
444
+ saveJob(job, { installedAt: new Date().toISOString() });
445
+ logLine(job.id, `installed: ${where}`);
446
+ emit({ job, installed: true, where }, () => { out(`Installed: ${where}.`); out(`Every day at ${String(hour).padStart(2, "0")}:${String(minute).padStart(2, "0")} this computer sends ${type} to Dumbo Pay. Try it now: dumbopay schedule test ${job.id}`); });
447
+ }
448
+ async function scheduleStatus() {
449
+ const ids = Object.keys(savedJobs());
450
+ const jobs = [];
451
+ for (const id of ids) { try { jobs.push((await call("GET", `/api/integrations/schedules/${id}`)).job); } catch (e) { jobs.push({ id, status: `unknown (${e.message})`, type: savedJobs()[id].type, path: savedJobs()[id].path, hour: savedJobs()[id].hour, minute: savedJobs()[id].minute }); } }
452
+ emit({ jobs }, () => { if (!jobs.length) { out("No nightly jobs on this computer. Set one up: dumbopay schedule install sales /path/to/export.csv --at 02:30"); return; } table(jobs, [["id", (j) => j.id.slice(0, 8)], ["type", (j) => j.type], ["path", (j) => j.path], ["at", (j) => `${String(j.hour).padStart(2, "0")}:${String(j.minute).padStart(2, "0")}`], ["status", (j) => statusLine(j)], ["last run", (j) => (j.lastRunAt ? `${j.lastOutcome} ${j.lastRunAt}` : "")]]); });
453
+ }
454
+ async function scheduleRemove(idArg) {
455
+ const ids = Object.keys(savedJobs()); const id = idArg ? ids.find((x) => x === idArg || x.startsWith(idArg)) ?? idArg : ids.length === 1 ? ids[0] : null;
456
+ if (!id) fail(ids.length ? `Say which job: ${ids.join(", ")}` : "No nightly jobs on this computer.", 2);
457
+ removeEntry(id); forgetJob(id); logLine(id, "removed from this computer");
458
+ emit({ ok: true, id }, () => out(`Removed the scheduled job ${id.slice(0, 8)} from this computer. The owner can also revoke it in Business Pro → Connections.`));
459
+ }
460
+ async function scheduleRun(idArg, verbose) {
461
+ const ids = Object.keys(savedJobs()); const id = ids.find((x) => x === idArg || x.startsWith(idArg)) ?? idArg;
462
+ let job;
463
+ try { job = (await call("GET", `/api/integrations/schedules/${id}`)).job; }
464
+ catch (e) { logLine(id, `could not check the job: ${e.message}`); if (e.code === 3) { removeEntry(id); forgetJob(id); logLine(id, "key refused: removed the scheduled entry"); } throw e; }
465
+ if (job.status !== "approved") { removeEntry(id); forgetJob(id); logLine(id, `job is ${job.status}: removed the scheduled entry`); fail(`This job is ${job.status}; the scheduled entry was removed from this computer.`, 4); }
466
+ const report = (outcome, message, extra = {}) => call("POST", `/api/integrations/schedules/${id}/ping`, { body: { outcome, message: String(message).slice(0, 500), ...extra } }).catch((e) => { logLine(id, `report failed: ${e.message}`); if (e.message && /revoked|declined/.test(e.message)) { removeEntry(id); forgetJob(id); } });
467
+ let file = job.path;
468
+ try {
469
+ if (job.mode === "newest") {
470
+ const csvs = readdirSync(job.path).filter((f) => /\.csv$/i.test(f)).map((f) => ({ f, t: statSync(join(job.path, f)).mtimeMs })).sort((a, b) => b.t - a.t);
471
+ if (!csvs.length) { logLine(id, "no .csv in the folder"); await report("skipped", "No .csv file in the folder yet."); emit({ outcome: "skipped" }, () => out("No .csv file in the folder yet.")); return; }
472
+ file = join(job.path, csvs[0].f);
473
+ }
474
+ if (!existsSync(file)) { logLine(id, `file missing: ${file}`); await report("skipped", `The file isn't there yet: ${basename(file)}.`, { file: basename(file) }); emit({ outcome: "skipped", file }, () => out(`The file isn't there yet: ${file}`)); return; }
475
+ const buf = readFileSync(file); if (buf.length > 3 * 1024 * 1024) throw new CliError("The file is over 3 MB; split the export.", 2);
476
+ const hash = sha256(buf);
477
+ if (job.lastFileHash && job.lastFileHash === hash) { logLine(id, `unchanged since last time: ${basename(file)}`); await report("skipped", `${basename(file)} is the same file as last time; nothing new to send.`, { file: basename(file) }); emit({ outcome: "skipped", file, reason: "unchanged" }, () => out(`${basename(file)} hasn't changed since the last run; nothing sent.`)); return; }
478
+ const r = await call("POST", `/api/integrations/exports/${job.type}`, { text: buf.toString("utf8"), headers: { "x-filename": basename(file) } });
479
+ const i = r.import || r; const rows = i.rowsOk ?? i.rows ?? 0;
480
+ await report("ok", `${basename(file)}: ${i.summary || `${rows} rows`}`, { file: basename(file), fileHash: hash, rows });
481
+ logLine(id, `sent ${basename(file)} (${rows} rows)`);
482
+ emit({ outcome: "ok", file, rows, import: i }, () => out(`Sent ${basename(file)} as ${job.type}: ${i.summary || `${rows} rows`}.`));
483
+ } catch (e) {
484
+ logLine(id, `failed: ${e.message}`);
485
+ await report("failed", e.message, { file: basename(file) });
486
+ if (verbose) throw e; else fail(e.message, e instanceof CliError ? e.code : 1);
487
+ }
488
+ }
489
+
327
490
  try {
328
491
  const name = !command || flags.help ? "help" : flags.version ? "version" : command;
329
492
  const fn = commands[name];
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dumbopay/cli",
3
- "version": "0.1.0",
3
+ "version": "0.2.0",
4
4
  "description": "The Dumbo Pay command line for stores: send register exports, read and correct inventory, pull readouts, reports and the books, from a terminal or a scheduled job, with a store key made in Business Pro.",
5
5
  "license": "MIT",
6
6
  "type": "module",