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