@dumbopay/cli 0.0.0-stage → 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 +27 -2
- package/bin/dumbopay.mjs +500 -0
- package/package.json +11 -4
package/README.md
CHANGED
|
@@ -1,3 +1,28 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @dumbopay/cli
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
The Dumbo Pay command line for stores: send register exports, read and correct inventory, pull the store readout, item movement, alerts and the month's books for QuickBooks or Xero, from a terminal, a script or a nightly job. One file, no dependencies, Node 20 or newer.
|
|
4
|
+
|
|
5
|
+
```
|
|
6
|
+
npm install -g @dumbopay/cli # or: npx @dumbopay/cli …
|
|
7
|
+
dumbopay login --key dpx_… # a store key from Business Pro → Connections → Store keys
|
|
8
|
+
dumbopay whoami
|
|
9
|
+
dumbopay import items ~/exports/items.csv
|
|
10
|
+
dumbopay inventory list --filter low
|
|
11
|
+
dumbopay inventory adjust 012345678905 count 24 --note "Shelf count"
|
|
12
|
+
dumbopay readout
|
|
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)
|
|
15
|
+
```
|
|
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.
|
|
18
|
+
|
|
19
|
+
- `--json` on any command gives machine-readable output; errors come back as `{ "error", "code" }`.
|
|
20
|
+
- `DUMBOPAY_KEY` in the environment overrides the saved key (servers, scheduled jobs). `DUMBOPAY_API` points at another server, for example staging.
|
|
21
|
+
- The saved key lives in `~/.config/dumbopay/config.json`, readable by you only.
|
|
22
|
+
- Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in or key refused, 4 permission denied, 5 Business Pro license needed.
|
|
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
|
+
|
|
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
ADDED
|
@@ -0,0 +1,500 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// The Dumbo Pay command line for stores. One file, no dependencies, Node 20 or newer.
|
|
3
|
+
// Signs every request with a store key made in Business Pro → Connections → Store keys.
|
|
4
|
+
//
|
|
5
|
+
// dumbopay login [--key dpx_…] [--api https://dumbopay.net]
|
|
6
|
+
// dumbopay whoami | store | connections
|
|
7
|
+
// dumbopay import <sales|items|stock|schedule|timeclock> <file.csv> [--dry-run]
|
|
8
|
+
// dumbopay templates <type>
|
|
9
|
+
// dumbopay inventory list|find|set|adjust|movements|import
|
|
10
|
+
// dumbopay departments [add <name>] | vendors [add <name>]
|
|
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>
|
|
14
|
+
// dumbopay api <METHOD> <path> [--data '{…}']
|
|
15
|
+
//
|
|
16
|
+
// Exit codes: 0 ok, 1 error, 2 usage, 3 not signed in / key refused, 4 permission denied, 5 license.
|
|
17
|
+
|
|
18
|
+
import { createInterface } from "node:readline";
|
|
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";
|
|
25
|
+
|
|
26
|
+
const VERSION = "0.2.0";
|
|
27
|
+
const DEFAULT_API = "https://dumbopay.net";
|
|
28
|
+
const CONFIG_DIR = process.env.DUMBOPAY_CONFIG_DIR || join(homedir(), ".config", "dumbopay");
|
|
29
|
+
const CONFIG_FILE = join(CONFIG_DIR, "config.json");
|
|
30
|
+
const IMPORT_TYPES = ["sales", "items", "stock", "schedule", "timeclock"];
|
|
31
|
+
|
|
32
|
+
// ---------------------------------------------------------------------------
|
|
33
|
+
// Arguments
|
|
34
|
+
// ---------------------------------------------------------------------------
|
|
35
|
+
|
|
36
|
+
const argv = process.argv.slice(2);
|
|
37
|
+
const flags = {}; const positional = [];
|
|
38
|
+
for (let i = 0; i < argv.length; i++) {
|
|
39
|
+
const a = argv[i];
|
|
40
|
+
if (a === "--") { positional.push(...argv.slice(i + 1)); break; }
|
|
41
|
+
if (a.startsWith("--")) {
|
|
42
|
+
const eq = a.indexOf("=");
|
|
43
|
+
const name = eq > 0 ? a.slice(2, eq) : a.slice(2);
|
|
44
|
+
const value = eq > 0 ? a.slice(eq + 1) : (argv[i + 1] !== undefined && !argv[i + 1].startsWith("--") ? argv[++i] : true);
|
|
45
|
+
if (name in flags) flags[name] = [].concat(flags[name], value); else flags[name] = value;
|
|
46
|
+
} else positional.push(a);
|
|
47
|
+
}
|
|
48
|
+
const JSON_OUT = Boolean(flags.json);
|
|
49
|
+
const [command, sub, ...rest] = positional;
|
|
50
|
+
|
|
51
|
+
class CliError extends Error { constructor(message, code = 1) { super(message); this.code = code; } }
|
|
52
|
+
const fail = (message, code = 1) => { throw new CliError(message, code); };
|
|
53
|
+
const out = (s = "") => process.stdout.write(`${s}\n`);
|
|
54
|
+
const emit = (data, human) => { if (JSON_OUT) out(JSON.stringify(data, null, 2)); else human(); };
|
|
55
|
+
const flag = (name, fallback) => (flags[name] === undefined || flags[name] === true ? fallback : String(flags[name]));
|
|
56
|
+
const need = (value, what) => value ?? fail(`Missing ${what}.`, 2);
|
|
57
|
+
const num = (v, what) => { const n = Number(String(v).replace(/[,$]/g, "")); if (!Number.isFinite(n)) fail(`${what} must be a number.`, 2); return n; };
|
|
58
|
+
|
|
59
|
+
// ---------------------------------------------------------------------------
|
|
60
|
+
// Config
|
|
61
|
+
// ---------------------------------------------------------------------------
|
|
62
|
+
|
|
63
|
+
function readConfig() { try { return JSON.parse(readFileSync(CONFIG_FILE, "utf8")); } catch { return {}; } }
|
|
64
|
+
function writeConfig(cfg) {
|
|
65
|
+
mkdirSync(CONFIG_DIR, { recursive: true, mode: 0o700 });
|
|
66
|
+
writeFileSync(CONFIG_FILE, JSON.stringify(cfg, null, 2) + "\n", { mode: 0o600 });
|
|
67
|
+
try { chmodSync(CONFIG_FILE, 0o600); } catch { /* Windows */ }
|
|
68
|
+
}
|
|
69
|
+
const config = readConfig();
|
|
70
|
+
const API = String(flags.api || process.env.DUMBOPAY_API || config.api || DEFAULT_API).replace(/\/+$/, "");
|
|
71
|
+
const KEY = process.env.DUMBOPAY_KEY || config.key || null;
|
|
72
|
+
|
|
73
|
+
// ---------------------------------------------------------------------------
|
|
74
|
+
// HTTP
|
|
75
|
+
// ---------------------------------------------------------------------------
|
|
76
|
+
|
|
77
|
+
async function call(method, path, { body, text, raw = false, key = KEY, headers: extra = {} } = {}) {
|
|
78
|
+
if (!key) fail("Not signed in. Run `dumbopay login` with a store key from Business Pro → Connections.", 3);
|
|
79
|
+
const headers = { authorization: `Bearer ${key}`, "user-agent": `dumbopay-cli/${VERSION}`, ...extra };
|
|
80
|
+
let payload;
|
|
81
|
+
if (text !== undefined) { headers["content-type"] = headers["content-type"] || "text/csv"; payload = text; }
|
|
82
|
+
else if (body !== undefined) { headers["content-type"] = "application/json"; payload = JSON.stringify(body); }
|
|
83
|
+
let res;
|
|
84
|
+
try { res = await fetch(`${API}${path}`, { method, headers, body: payload }); }
|
|
85
|
+
catch (e) { fail(`Couldn't reach ${API}: ${e.message}`); }
|
|
86
|
+
if (raw) {
|
|
87
|
+
if (!res.ok) { const err = await res.json().catch(() => ({})); throw httpError(res.status, err); }
|
|
88
|
+
return res;
|
|
89
|
+
}
|
|
90
|
+
const type = res.headers.get("content-type") || "";
|
|
91
|
+
const data = type.includes("json") ? await res.json().catch(() => ({})) : await res.text();
|
|
92
|
+
if (!res.ok) throw httpError(res.status, data);
|
|
93
|
+
return data;
|
|
94
|
+
}
|
|
95
|
+
function httpError(status, data) {
|
|
96
|
+
const message = (data && typeof data === "object" && data.error) || `HTTP ${status}`;
|
|
97
|
+
if (status === 401) return new CliError(`${message} (run \`dumbopay login\` with a valid key)`, 3);
|
|
98
|
+
if (status === 403) return new CliError(message, 4);
|
|
99
|
+
if (status === 402) return new CliError(`${message} (Business Pro license)`, 5);
|
|
100
|
+
return new CliError(message, 1);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// ---------------------------------------------------------------------------
|
|
104
|
+
// Helpers
|
|
105
|
+
// ---------------------------------------------------------------------------
|
|
106
|
+
|
|
107
|
+
function table(rows, columns) {
|
|
108
|
+
if (rows.length === 0) { out("(nothing)"); return; }
|
|
109
|
+
const cells = rows.map((r) => columns.map(([, get]) => String(get(r) ?? "")));
|
|
110
|
+
const widths = columns.map(([h], i) => Math.min(48, Math.max(h.length, ...cells.map((c) => c[i].length))));
|
|
111
|
+
const line = (parts) => parts.map((p, i) => p.slice(0, widths[i]).padEnd(widths[i])).join(" ");
|
|
112
|
+
out(line(columns.map(([h]) => h)));
|
|
113
|
+
out(line(widths.map((w) => "-".repeat(w))));
|
|
114
|
+
for (const c of cells) out(line(c));
|
|
115
|
+
}
|
|
116
|
+
const money = (cents) => (cents === null || cents === undefined ? "" : `$${(Number(cents) / 100).toLocaleString("en-US", { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`);
|
|
117
|
+
const day = (s) => (s ? String(s).slice(0, 10) : "");
|
|
118
|
+
const readText = (path) => { const abs = resolve(path); if (!existsSync(abs)) fail(`No such file: ${path}`, 2); if (statSync(abs).size > 3 * 1024 * 1024) fail("Files over 3 MB must be split (5,000 rows at a time).", 2); return readFileSync(abs, "utf8"); };
|
|
119
|
+
async function ask(prompt, { hidden = false } = {}) {
|
|
120
|
+
if (!process.stdin.isTTY) fail(`${prompt} is required when not in a terminal; pass it as a flag.`, 2);
|
|
121
|
+
return new Promise((resolveAnswer) => {
|
|
122
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout, terminal: true });
|
|
123
|
+
if (hidden) { rl._writeToOutput = (s) => { if (s.includes(prompt)) process.stdout.write(prompt); }; }
|
|
124
|
+
rl.question(`${prompt}: `, (answer) => { rl.close(); if (hidden) process.stdout.write("\n"); resolveAnswer(answer.trim()); });
|
|
125
|
+
});
|
|
126
|
+
}
|
|
127
|
+
async function saveResponse(res, outPath, fallbackName) {
|
|
128
|
+
const cd = res.headers.get("content-disposition") || "";
|
|
129
|
+
const suggested = /filename="?([^";]+)"?/.exec(cd)?.[1] || fallbackName;
|
|
130
|
+
const target = resolve(outPath || suggested);
|
|
131
|
+
writeFileSync(target, Buffer.from(await res.arrayBuffer()));
|
|
132
|
+
return target;
|
|
133
|
+
}
|
|
134
|
+
/** A small CSV reader (quoted fields, commas) for `inventory import`. */
|
|
135
|
+
function parseCsv(text) {
|
|
136
|
+
const rows = []; let row = []; let cell = ""; let quoted = false;
|
|
137
|
+
for (let i = 0; i < text.length; i++) {
|
|
138
|
+
const ch = text[i];
|
|
139
|
+
if (quoted) { if (ch === '"') { if (text[i + 1] === '"') { cell += '"'; i++; } else quoted = false; } else cell += ch; continue; }
|
|
140
|
+
if (ch === '"') quoted = true;
|
|
141
|
+
else if (ch === ",") { row.push(cell); cell = ""; }
|
|
142
|
+
else if (ch === "\n" || ch === "\r") { if (ch === "\r" && text[i + 1] === "\n") i++; row.push(cell); rows.push(row); row = []; cell = ""; }
|
|
143
|
+
else cell += ch;
|
|
144
|
+
}
|
|
145
|
+
if (cell.length || row.length) { row.push(cell); rows.push(row); }
|
|
146
|
+
return rows.filter((r) => r.some((c) => c.trim() !== ""));
|
|
147
|
+
}
|
|
148
|
+
const BO = "/api/backoffice/mine";
|
|
149
|
+
async function findItem(skuOrId) {
|
|
150
|
+
if (/^\d+$/.test(skuOrId)) { const r = await call("GET", `${BO}/inventory?q=${encodeURIComponent(skuOrId)}`); const hit = r.items.find((i) => String(i.id) === skuOrId || i.sku === skuOrId); if (hit) return hit; }
|
|
151
|
+
const r = await call("GET", `${BO}/inventory?q=${encodeURIComponent(skuOrId)}`);
|
|
152
|
+
const exact = r.items.find((i) => i.sku === skuOrId);
|
|
153
|
+
if (exact) return exact;
|
|
154
|
+
if (r.items.length === 1) return r.items[0];
|
|
155
|
+
if (r.items.length === 0) fail(`No item with code ${skuOrId}.`, 2);
|
|
156
|
+
fail(`Several items match "${skuOrId}": ${r.items.slice(0, 5).map((i) => `${i.sku || "?"} ${i.name}`).join("; ")}. Use the exact code.`, 2);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// ---------------------------------------------------------------------------
|
|
160
|
+
// Commands
|
|
161
|
+
// ---------------------------------------------------------------------------
|
|
162
|
+
|
|
163
|
+
const commands = {
|
|
164
|
+
async login() {
|
|
165
|
+
const key = flag("key") || (await ask("Store key (dpx_…)", { hidden: true }));
|
|
166
|
+
if (!/^dpx_[0-9a-f]{64}$/.test(key)) fail("That doesn't look like a Dumbo Pay store key (dpx_ followed by 64 characters).", 2);
|
|
167
|
+
const me = await call("GET", "/api/integrations/me", { key });
|
|
168
|
+
writeConfig({ ...config, api: API, key });
|
|
169
|
+
emit({ ok: true, api: API, email: me.user.email, store: me.store, key: me.key }, () => {
|
|
170
|
+
out(`Signed in to ${API} as ${me.user.email}${me.store ? ` for ${me.store.name}` : ""}${me.key?.label ? ` with key "${me.key.label}"` : ""}. Saved to ${CONFIG_FILE}.`);
|
|
171
|
+
if (me.key) out(`Permissions: ${me.key.scopes.join(", ")}${me.key.expiresAt ? ` · expires ${day(me.key.expiresAt)}` : ""}`);
|
|
172
|
+
});
|
|
173
|
+
},
|
|
174
|
+
async logout() {
|
|
175
|
+
if (existsSync(CONFIG_FILE)) unlinkSync(CONFIG_FILE);
|
|
176
|
+
emit({ ok: true }, () => out("Signed out; the saved key was removed from this computer. Revoke it in Business Pro if it shouldn't be used again."));
|
|
177
|
+
},
|
|
178
|
+
async whoami() {
|
|
179
|
+
const me = await call("GET", "/api/integrations/me");
|
|
180
|
+
emit({ api: API, ...me }, () => {
|
|
181
|
+
out(`${me.user.name || me.user.email} <${me.user.email}> on ${API}`);
|
|
182
|
+
if (me.store) out(`Store: ${me.store.name} (${me.store.role === "business_owner" ? "owner" : "staff"})`); else out("No store on this account.");
|
|
183
|
+
if (me.key) out(`Key "${me.key.label || "…" + me.key.hint}": ${me.key.scopes.join(", ")}${me.key.expiresAt ? ` · expires ${day(me.key.expiresAt)}` : ""}`);
|
|
184
|
+
});
|
|
185
|
+
},
|
|
186
|
+
async store() {
|
|
187
|
+
const r = await call("GET", `${BO}/summary`);
|
|
188
|
+
emit(r, () => {
|
|
189
|
+
const flat = (obj, prefix = "") => Object.entries(obj || {}).flatMap(([k, v]) => (v && typeof v === "object" && !Array.isArray(v) ? flat(v, `${prefix}${k}.`) : Array.isArray(v) ? [[`${prefix}${k}`, `${v.length} item(s)`]] : [[`${prefix}${k}`, v]]));
|
|
190
|
+
table(flat(r), [["figure", (x) => x[0]], ["value", (x) => x[1]]]);
|
|
191
|
+
});
|
|
192
|
+
},
|
|
193
|
+
async connections() {
|
|
194
|
+
const r = await call("GET", "/api/business/connections");
|
|
195
|
+
emit(r, () => {
|
|
196
|
+
out("Systems:"); table(Object.entries(r.systems || {}), [["kind", (e) => e[0]], ["system", (e) => e[1]?.name || "not answered"]]);
|
|
197
|
+
out("\nConnections:"); table(r.connections || [], [["kind", (c) => c.kind], ["method", (c) => c.method || ""], ["status", (c) => c.status], ["last sync", (c) => c.lastSyncAt || ""]]);
|
|
198
|
+
out(`\nKeys: ${(r.keys || []).length} · Imports on record: ${(r.imports || []).length}`);
|
|
199
|
+
});
|
|
200
|
+
},
|
|
201
|
+
|
|
202
|
+
async import() {
|
|
203
|
+
const type = need(sub, `a file type (${IMPORT_TYPES.join(", ")})`); if (!IMPORT_TYPES.includes(type)) fail(`The type is one of ${IMPORT_TYPES.join(", ")}.`, 2);
|
|
204
|
+
const path = need(rest[0], "a CSV file"); const text = readText(path);
|
|
205
|
+
if (flags["dry-run"]) {
|
|
206
|
+
const r = await call("POST", "/api/business/connections/imports/preview", { body: { type, filename: basename(path), text } });
|
|
207
|
+
emit(r, () => { out(`Dry run of ${basename(path)} as ${type}: ${r.rows ?? r.totalRows ?? "?"} row(s).`); if (r.mapping) { out("Columns matched:"); table(Object.entries(r.mapping), [["field", (e) => e[0]], ["column", (e) => String(e[1])]]); } if (r.missing?.length) out(`Missing required: ${r.missing.join(", ")}`); if (r.problems?.length) for (const p of r.problems.slice(0, 20)) out(` ${typeof p === "string" ? p : JSON.stringify(p)}`); });
|
|
208
|
+
return;
|
|
209
|
+
}
|
|
210
|
+
const r = await call("POST", `/api/integrations/exports/${type}`, { text, headers: { "x-filename": basename(path) } });
|
|
211
|
+
emit(r, () => { const i = r.import || r; out(`Imported ${basename(path)} as ${type}${i.rows !== undefined ? `: ${i.rows} row(s)` : ""}${i.applied !== undefined ? `, ${i.applied} applied` : ""}${i.skipped !== undefined ? `, ${i.skipped} skipped` : ""}${i.unknown !== undefined ? `, ${Array.isArray(i.unknown) ? i.unknown.length : i.unknown} unknown code(s)` : ""}.`); if (i.notes?.length) for (const n of i.notes) out(` ${n}`); });
|
|
212
|
+
},
|
|
213
|
+
async templates() {
|
|
214
|
+
const type = need(sub, `a file type (${IMPORT_TYPES.join(", ")})`);
|
|
215
|
+
const res = await call("GET", `/api/business/connections/templates/${type}`, { raw: true });
|
|
216
|
+
const text = await res.text();
|
|
217
|
+
if (flags.out) { writeFileSync(resolve(String(flags.out)), text); out(`Saved ${resolve(String(flags.out))}`); } else out(text.trim());
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
async inventory() {
|
|
221
|
+
switch (sub || "list") {
|
|
222
|
+
case "list": {
|
|
223
|
+
const q = new URLSearchParams(); if (flags.q) q.set("q", String(flags.q)); if (flags.filter) q.set("filter", String(flags.filter)); if (flags.department) q.set("department", String(flags.department)); if (flags.page) q.set("page", String(flags.page));
|
|
224
|
+
const r = await call("GET", `${BO}/inventory${q.toString() ? `?${q}` : ""}`);
|
|
225
|
+
emit(r, () => { table(r.items, [["id", (i) => i.id], ["code", (i) => i.sku || ""], ["name", (i) => i.name], ["price", (i) => money(i.priceCents)], ["on hand", (i) => i.onHand ?? "—"], ["reorder at", (i) => i.reorderPoint ?? ""], ["cost", (i) => money(i.unitCostCents)], ["department", (i) => i.department || ""]]); out(`${r.items.length} of ${r.total} (page ${r.page})`); }); return;
|
|
226
|
+
}
|
|
227
|
+
case "find": { const item = await findItem(need(rest[0], "an item code or id")); emit(item, () => { out(`${item.name} · code ${item.sku || "?"} · id ${item.id}`); out(`Price ${money(item.priceCents)} · cost ${money(item.unitCostCents) || "?"} · on hand ${item.onHand ?? "not tracked"} · reorder at ${item.reorderPoint ?? "—"} (${item.reorderQty ?? "—"})`); out(`Department ${item.department || "—"} · vendor ${item.vendor || "—"}`); }); return; }
|
|
228
|
+
case "set": {
|
|
229
|
+
const item = await findItem(need(rest[0], "an item code or id"));
|
|
230
|
+
const bodyOut = {
|
|
231
|
+
track: flags.track !== undefined ? flags.track !== "false" : flags["no-track"] ? false : item.onHand !== null && item.onHand !== undefined,
|
|
232
|
+
reorderPoint: flags["reorder-point"] !== undefined ? num(flags["reorder-point"], "--reorder-point") : item.reorderPoint ?? null,
|
|
233
|
+
reorderQty: flags["reorder-qty"] !== undefined ? num(flags["reorder-qty"], "--reorder-qty") : item.reorderQty ?? null,
|
|
234
|
+
unitCostCents: flags.cost !== undefined ? Math.round(num(flags.cost, "--cost") * 100) : item.unitCostCents ?? null,
|
|
235
|
+
vendorId: flags.vendor !== undefined ? num(flags.vendor, "--vendor") : item.vendorId ?? null,
|
|
236
|
+
departmentId: flags.department !== undefined ? num(flags.department, "--department") : item.departmentId ?? null,
|
|
237
|
+
};
|
|
238
|
+
await call("PUT", `${BO}/inventory/${item.id}`, { body: bodyOut });
|
|
239
|
+
emit({ ok: true, id: item.id, ...bodyOut }, () => out(`Updated ${item.name}.`)); return;
|
|
240
|
+
}
|
|
241
|
+
case "adjust": {
|
|
242
|
+
const item = await findItem(need(rest[0], "an item code or id")); const kind = need(rest[1], "a kind: count, adjust, waste, return"); const quantity = num(need(rest[2], "a quantity"), "quantity");
|
|
243
|
+
const r = await call("POST", `${BO}/inventory/${item.id}/adjust`, { body: { kind, quantity, note: flag("note", "") } });
|
|
244
|
+
emit({ ok: true, id: item.id, onHand: r.onHand }, () => out(`${item.name}: ${kind} ${quantity} → on hand ${r.onHand}.`)); return;
|
|
245
|
+
}
|
|
246
|
+
case "movements": { const item = await findItem(need(rest[0], "an item code or id")); const r = await call("GET", `${BO}/inventory/${item.id}/movements`); emit(r, () => table(r.movements, [["when", (m) => String(m.created_at).slice(0, 16)], ["kind", (m) => m.kind], ["qty", (m) => m.quantity], ["after", (m) => m.on_hand_after], ["note", (m) => m.note || ""]])); return; }
|
|
247
|
+
case "import": {
|
|
248
|
+
const rows = parseCsv(readText(need(rest[0], "a CSV with sku,on_hand,cost,reorder_point,department")));
|
|
249
|
+
const header = rows[0].map((h) => h.toLowerCase().replace(/[^a-z0-9]/g, ""));
|
|
250
|
+
const col = (...names) => header.findIndex((h) => names.includes(h));
|
|
251
|
+
const iSku = col("sku", "upc", "barcode", "plu", "itemcode", "code"), iOn = col("onhand", "qoh", "stock", "count", "quantity", "qty"), iCost = col("cost", "unitcost"), iRp = col("reorderpoint", "reorder", "min", "par"), iDept = col("department", "dept", "category");
|
|
252
|
+
if (iSku < 0) fail("The CSV needs a sku (or upc/plu) column.", 2);
|
|
253
|
+
const body = rows.slice(1).map((r) => ({ sku: r[iSku]?.trim(), ...(iOn >= 0 && r[iOn]?.trim() !== "" ? { onHand: Number(r[iOn]) } : {}), ...(iCost >= 0 && r[iCost]?.trim() !== "" ? { unitCostCents: Math.round(Number(String(r[iCost]).replace(/[,$]/g, "")) * 100) } : {}), ...(iRp >= 0 && r[iRp]?.trim() !== "" ? { reorderPoint: Number(r[iRp]) } : {}), ...(iDept >= 0 && r[iDept]?.trim() ? { department: r[iDept].trim() } : {}) })).filter((r) => r.sku);
|
|
254
|
+
let matched = 0; const unknown = [];
|
|
255
|
+
for (let i = 0; i < body.length; i += 100) { const r = await call("POST", `${BO}/inventory/import`, { body: { rows: body.slice(i, i + 100) } }); matched += r.matched; unknown.push(...(r.unknown || [])); }
|
|
256
|
+
emit({ rows: body.length, matched, unknown }, () => { out(`${body.length} row(s): ${matched} matched.`); if (unknown.length) out(`Unknown codes (${unknown.length}): ${unknown.slice(0, 20).join(", ")}${unknown.length > 20 ? "…" : ""}`); }); return;
|
|
257
|
+
}
|
|
258
|
+
default: fail(`Unknown: inventory ${sub}. Try list, find, set, adjust, movements, import.`, 2);
|
|
259
|
+
}
|
|
260
|
+
},
|
|
261
|
+
async departments() {
|
|
262
|
+
if (sub === "add") { const r = await call("POST", `${BO}/departments`, { body: { name: need(rest[0], "a name"), posCode: flag("pos-code", "") } }); emit(r, () => out(`Added department ${rest[0]}.`)); return; }
|
|
263
|
+
const r = await call("GET", `${BO}/departments`); const list = r.departments || r;
|
|
264
|
+
emit(r, () => table(list, [["id", (d) => d.id], ["name", (d) => d.name], ["POS code", (d) => d.posCode ?? d.pos_code ?? ""], ["items", (d) => d.products ?? d.items ?? ""]]));
|
|
265
|
+
},
|
|
266
|
+
async vendors() {
|
|
267
|
+
if (sub === "add") { const r = await call("POST", `${BO}/vendors`, { body: { name: need(rest[0], "a name"), contactName: flag("contact", ""), email: flag("email", ""), phone: flag("phone", ""), address: flag("address", ""), accountNumber: flag("account", "") } }); emit(r, () => out(`Added vendor ${rest[0]}.`)); return; }
|
|
268
|
+
const r = await call("GET", `${BO}/vendors`); const list = r.vendors || r;
|
|
269
|
+
emit(r, () => table(list, [["id", (v) => v.id], ["name", (v) => v.name], ["contact", (v) => v.contactName ?? v.contact_name ?? ""], ["phone", (v) => v.phone || ""]]));
|
|
270
|
+
},
|
|
271
|
+
|
|
272
|
+
async readout() {
|
|
273
|
+
const r = await call("GET", "/api/business/readouts");
|
|
274
|
+
emit(r, () => {
|
|
275
|
+
out(`${r.storeName} · ${r.daysSinceJoin} day(s) on Dumbo Pay${r.salesData ? "" : " · register sales not yet switched on"}`);
|
|
276
|
+
const m = (x) => Object.entries(x || {}).filter(([, v]) => typeof v === "number").map(([k, v]) => `${k} ${v}`).join(" · ");
|
|
277
|
+
out(`Last 7 days: ${m(r.last7)}`); out(`Previous 7: ${m(r.previous7)}`);
|
|
278
|
+
if (r.highlights?.length) { out("\nHighlights:"); for (const h of r.highlights) out(` • ${h}`); }
|
|
279
|
+
if (r.nextSteps?.length) { out("\nNext steps:"); for (const s of r.nextSteps) out(` → ${typeof s === "string" ? s : s.title || s.text || JSON.stringify(s)}`); }
|
|
280
|
+
});
|
|
281
|
+
},
|
|
282
|
+
async movement() {
|
|
283
|
+
const q = new URLSearchParams(); q.set("period", flag("period", "week")); if (flags.date) q.set("date", String(flags.date));
|
|
284
|
+
if (flags.csv) { q.set("format", "csv"); const res = await call("GET", `/api/business/reports/movement?${q}`, { raw: true }); const target = await saveResponse(res, flags.csv === true ? undefined : String(flags.csv), "item-movement.csv"); emit({ ok: true, path: target }, () => out(`Saved ${target}`)); return; }
|
|
285
|
+
const r = await call("GET", `/api/business/reports/movement?${q}`);
|
|
286
|
+
emit(r, () => { out(`Item movement, ${r.period} ${r.from} → ${r.to}${r.integrations ? "" : " (register movements off)"}`); table((r.rows || []).slice(0, Number(flag("limit", "50"))), [["code", (x) => x.sku || ""], ["item", (x) => x.name], ["online", (x) => x.onlineUnits ?? ""], ["register", (x) => x.registerUnits ?? ""], ["revenue", (x) => money(((x.onlineRevenue ?? 0) + (x.registerRevenue ?? 0)) * 100)], ["vs prev", (x) => x.previousUnits ?? ""]]); out(`Totals: ${Object.entries(r.totals || {}).map(([k, v]) => `${k} ${v}`).join(" · ")}`); });
|
|
287
|
+
},
|
|
288
|
+
async alerts() {
|
|
289
|
+
if (sub === "dismiss") { const r = await call("POST", `/api/business/reports/alerts/${need(rest[0], "an alert id")}/dismiss`, { body: {} }); emit(r, () => out(`Dismissed. ${r.alerts.length} alert(s) open.`)); return; }
|
|
290
|
+
const r = flags.refresh ? await call("POST", "/api/business/reports/alerts/refresh", { body: {} }) : await call("GET", "/api/business/reports/alerts");
|
|
291
|
+
emit(r, () => table(r.alerts || [], [["id", (a) => a.id], ["kind", (a) => a.kind], ["item", (a) => a.name || a.productName || ""], ["message", (a) => a.message || a.summary || ""], ["since", (a) => day(a.createdAt || a.created_at)]]));
|
|
292
|
+
},
|
|
293
|
+
async accounting() {
|
|
294
|
+
const kind = need(sub, "a file kind: sales, rewards, bills, journal");
|
|
295
|
+
const q = new URLSearchParams(); if (flags.month) q.set("month", String(flags.month)); if (flags.software) q.set("software", String(flags.software));
|
|
296
|
+
const res = await call("GET", `/api/integrations/accounting/${kind}?${q}`, { raw: true });
|
|
297
|
+
const target = await saveResponse(res, flags.out, `${kind}.csv`);
|
|
298
|
+
emit({ ok: true, path: target, rows: Number(res.headers.get("x-rows") || 0) }, () => out(`Saved ${target} (${res.headers.get("x-rows") || "?"} rows)`));
|
|
299
|
+
},
|
|
300
|
+
async kiosks() {
|
|
301
|
+
const r = await call("GET", "/api/kiosk-admin/devices");
|
|
302
|
+
emit(r, () => { table(r.devices || [], [["name", (d) => d.name], ["paired", (d) => (d.paired ? "yes" : "no")], ["online", (d) => (d.online ? "yes" : "no")], ["last seen", (d) => d.lastSeenAt || ""], ["client", (d) => d.client ? `${d.client.kind}${d.client.version ? ` ${d.client.version}` : ""}` : ""], ["update", (d) => (d.updateAvailable ? "available" : "")]]); out(`Agreement signed: ${r.agreementSigned ? "yes" : "no"}${r.latestVersion ? ` · latest kiosk program ${r.latestVersion}` : ""}`); });
|
|
303
|
+
},
|
|
304
|
+
async api() {
|
|
305
|
+
const method = String(need(sub, "a method (GET, POST, PUT, DELETE)")).toUpperCase();
|
|
306
|
+
const path = need(rest[0], "a path like /api/business/readouts");
|
|
307
|
+
const body = flags.data ? JSON.parse(String(flags.data)) : undefined;
|
|
308
|
+
const r = await call(method, path.startsWith("/") ? path : `/${path}`, { body });
|
|
309
|
+
out(typeof r === "string" ? r : JSON.stringify(r, null, 2));
|
|
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
|
+
},
|
|
324
|
+
version() { out(VERSION); },
|
|
325
|
+
help() {
|
|
326
|
+
out(`dumbopay ${VERSION}: the Dumbo Pay command line for stores.
|
|
327
|
+
|
|
328
|
+
dumbopay login [--key dpx_…] [--api URL] save a store key for this computer
|
|
329
|
+
dumbopay logout | whoami | store | connections
|
|
330
|
+
dumbopay import <sales|items|stock|schedule|timeclock> <file.csv> [--dry-run]
|
|
331
|
+
dumbopay templates <type> [--out file]
|
|
332
|
+
dumbopay inventory list [--q text --filter low|out|tracked|untracked --department id --page n]
|
|
333
|
+
dumbopay inventory find <code> | set <code> [--reorder-point n --reorder-qty n --cost 1.25 --department id --vendor id --no-track]
|
|
334
|
+
dumbopay inventory adjust <code> <count|adjust|waste|return> <qty> [--note …] | movements <code> | import <file.csv>
|
|
335
|
+
dumbopay departments [add <name> --pos-code x] | vendors [add <name> --contact --email --phone]
|
|
336
|
+
dumbopay readout | movement [--period day|week|month --date YYYY-MM-DD --csv [file]] | alerts [--refresh] | alerts dismiss <id>
|
|
337
|
+
dumbopay accounting <sales|rewards|bills|journal> [--month YYYY-MM --software quickbooks|xero|generic --out file]
|
|
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>
|
|
341
|
+
dumbopay api <METHOD> <path> [--data '{…}']
|
|
342
|
+
|
|
343
|
+
Everywhere: --json for machine-readable output, --api <url> for staging. Keys: Business Pro → Connections → Store keys.`);
|
|
344
|
+
},
|
|
345
|
+
};
|
|
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, "&").replace(/</g, "<");
|
|
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
|
+
|
|
490
|
+
try {
|
|
491
|
+
const name = !command || flags.help ? "help" : flags.version ? "version" : command;
|
|
492
|
+
const fn = commands[name];
|
|
493
|
+
if (!fn) fail(`Unknown command "${command}". Try \`dumbopay help\`.`, 2);
|
|
494
|
+
await fn();
|
|
495
|
+
} catch (e) {
|
|
496
|
+
const code = e instanceof CliError ? e.code : 1;
|
|
497
|
+
if (JSON_OUT) out(JSON.stringify({ error: e.message, code }));
|
|
498
|
+
else process.stderr.write(`dumbopay: ${e.message}\n`);
|
|
499
|
+
process.exit(code);
|
|
500
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,13 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@dumbopay/cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.2.0",
|
|
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
|
+
"license": "MIT",
|
|
6
|
+
"type": "module",
|
|
7
|
+
"bin": { "dumbopay": "bin/dumbopay.mjs" },
|
|
8
|
+
"files": ["bin", "README.md"],
|
|
9
|
+
"engines": { "node": ">=20" },
|
|
10
|
+
"keywords": ["dumbopay", "grocery", "pos", "inventory", "cli"],
|
|
11
|
+
"homepage": "https://dumbopay.net/for-stores",
|
|
12
|
+
"repository": { "type": "git", "url": "https://github.com/DumboPay/dumbopay", "directory": "cli" }
|
|
13
|
+
}
|