@dayzehq/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/LICENSE +21 -0
- package/README.md +305 -2
- package/dist/add.d.ts +6 -0
- package/dist/add.js +72 -0
- package/dist/admin.d.ts +110 -0
- package/dist/admin.js +408 -0
- package/dist/agent-bridge.d.ts +50 -0
- package/dist/agent-bridge.js +146 -0
- package/dist/agent-mcp.d.ts +4 -0
- package/dist/agent-mcp.js +36 -0
- package/dist/ai-consent.d.ts +18 -0
- package/dist/ai-consent.js +93 -0
- package/dist/args.d.ts +5 -0
- package/dist/args.js +127 -0
- package/dist/auth.d.ts +20 -0
- package/dist/auth.js +198 -0
- package/dist/channel.d.ts +55 -0
- package/dist/channel.js +250 -0
- package/dist/chat.d.ts +67 -0
- package/dist/chat.js +170 -0
- package/dist/cli-errors.d.ts +13 -0
- package/dist/cli-errors.js +30 -0
- package/dist/coding-context.d.ts +12 -0
- package/dist/coding-context.js +130 -0
- package/dist/coding.d.ts +35 -0
- package/dist/coding.js +283 -0
- package/dist/config.d.ts +36 -0
- package/dist/config.js +149 -0
- package/dist/day.d.ts +22 -0
- package/dist/day.js +54 -0
- package/dist/dayze-cli-runtime +0 -0
- package/dist/dayze-days.d.ts +56 -0
- package/dist/dayze-days.js +276 -0
- package/dist/doctor.d.ts +32 -0
- package/dist/doctor.js +225 -0
- package/dist/focus.d.ts +9 -0
- package/dist/focus.js +163 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.js +675 -0
- package/dist/inventory.d.ts +73 -0
- package/dist/inventory.js +1272 -0
- package/dist/life.d.ts +48 -0
- package/dist/life.js +146 -0
- package/dist/me.d.ts +94 -0
- package/dist/me.js +789 -0
- package/dist/people.d.ts +232 -0
- package/dist/people.js +2034 -0
- package/dist/projects.d.ts +21 -0
- package/dist/projects.js +132 -0
- package/dist/request-deadline.d.ts +11 -0
- package/dist/request-deadline.js +34 -0
- package/dist/runtime-build.json +1 -0
- package/dist/ui.d.ts +37 -0
- package/dist/ui.js +219 -0
- package/dist/version.d.ts +4 -0
- package/dist/version.js +16 -0
- package/package.json +54 -4
|
@@ -0,0 +1,1272 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Industry-standard Life Inventory / Closet for Dayze CLI.
|
|
3
|
+
*
|
|
4
|
+
* Same UX language as `dayze people` (fzf + file-manager hybrid):
|
|
5
|
+
* - Load inventory once, live type-ahead filter
|
|
6
|
+
* - Ctrl+S cycles sort · ↑↓ Enter detail
|
|
7
|
+
* - Detail: a agent · e edit · n note · Esc back
|
|
8
|
+
* - Plain `list` / `show` for scripts
|
|
9
|
+
*/
|
|
10
|
+
import readline from 'node:readline/promises';
|
|
11
|
+
import { stdin as input, stdout as output } from 'node:process';
|
|
12
|
+
import { authHeader } from './config.js';
|
|
13
|
+
import { askAgent } from './chat.js';
|
|
14
|
+
import { printJson } from './cli-errors.js';
|
|
15
|
+
import { fetchJsonWithDeadline } from './request-deadline.js';
|
|
16
|
+
import * as ui from './ui.js';
|
|
17
|
+
import { CLI_USER_AGENT } from './version.js';
|
|
18
|
+
import { INVENTORY_ADD_FIELDS, parseAddArgs, postAdd } from './add.js';
|
|
19
|
+
export const INVENTORY_SORT_CYCLE = [
|
|
20
|
+
'updated',
|
|
21
|
+
'name',
|
|
22
|
+
'price-desc',
|
|
23
|
+
'price-asc',
|
|
24
|
+
'purchased',
|
|
25
|
+
'category',
|
|
26
|
+
];
|
|
27
|
+
export function parseInventorySort(raw) {
|
|
28
|
+
if (!raw)
|
|
29
|
+
return null;
|
|
30
|
+
const s = raw.trim().toLowerCase();
|
|
31
|
+
if (s === 'name' || s === 'alpha' || s === 'a-z')
|
|
32
|
+
return 'name';
|
|
33
|
+
if (s === 'updated' || s === 'recent' || s === 'last')
|
|
34
|
+
return 'updated';
|
|
35
|
+
if (s === 'price' || s === 'price-desc' || s === 'value' || s === 'value-desc')
|
|
36
|
+
return 'price-desc';
|
|
37
|
+
if (s === 'price-asc' || s === 'cheap' || s === 'value-asc')
|
|
38
|
+
return 'price-asc';
|
|
39
|
+
if (s === 'purchased' || s === 'bought' || s === 'date' || s === 'purchase')
|
|
40
|
+
return 'purchased';
|
|
41
|
+
if (s === 'category' || s === 'cat' || s === 'type')
|
|
42
|
+
return 'category';
|
|
43
|
+
return null;
|
|
44
|
+
}
|
|
45
|
+
export function inventorySortLabel(sort) {
|
|
46
|
+
switch (sort) {
|
|
47
|
+
case 'name':
|
|
48
|
+
return 'name';
|
|
49
|
+
case 'updated':
|
|
50
|
+
return 'updated';
|
|
51
|
+
case 'price-desc':
|
|
52
|
+
return 'price↓';
|
|
53
|
+
case 'price-asc':
|
|
54
|
+
return 'price↑';
|
|
55
|
+
case 'purchased':
|
|
56
|
+
return 'bought';
|
|
57
|
+
case 'category':
|
|
58
|
+
return 'category';
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
const EDITABLE_FIELDS = [
|
|
62
|
+
{ key: 'name', label: 'Name' },
|
|
63
|
+
{ key: 'brand', label: 'Brand' },
|
|
64
|
+
{ key: 'item_type', label: 'Type' },
|
|
65
|
+
{ key: 'category', label: 'Category' },
|
|
66
|
+
{ key: 'color', label: 'Color' },
|
|
67
|
+
{ key: 'size', label: 'Size' },
|
|
68
|
+
{ key: 'condition', label: 'Condition' },
|
|
69
|
+
{ key: 'status', label: 'Status' },
|
|
70
|
+
{ key: 'purchase_price', label: 'Paid' },
|
|
71
|
+
{ key: 'current_value', label: 'Resell' },
|
|
72
|
+
{ key: 'currency', label: 'Currency' },
|
|
73
|
+
{ key: 'purchase_date', label: 'Bought' },
|
|
74
|
+
{ key: 'location', label: 'Location' },
|
|
75
|
+
{ key: 'notes', label: 'Notes' },
|
|
76
|
+
];
|
|
77
|
+
async function promptLine(question) {
|
|
78
|
+
const rl = readline.createInterface({ input, output });
|
|
79
|
+
try {
|
|
80
|
+
return (await rl.question(question)).trim();
|
|
81
|
+
}
|
|
82
|
+
finally {
|
|
83
|
+
rl.close();
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
function authFetchHeaders(creds) {
|
|
87
|
+
const header = authHeader(creds);
|
|
88
|
+
if (!header)
|
|
89
|
+
throw new Error('Not logged in');
|
|
90
|
+
return { Authorization: header, Accept: 'application/json', 'User-Agent': CLI_USER_AGENT };
|
|
91
|
+
}
|
|
92
|
+
export async function fetchInventoryPage(creds, opts = {}) {
|
|
93
|
+
const params = new URLSearchParams();
|
|
94
|
+
if (opts.q)
|
|
95
|
+
params.set('q', opts.q);
|
|
96
|
+
if (opts.category)
|
|
97
|
+
params.set('category', opts.category);
|
|
98
|
+
if (opts.status)
|
|
99
|
+
params.set('status', opts.status);
|
|
100
|
+
params.set('limit', String(opts.limit ?? 100));
|
|
101
|
+
params.set('offset', String(opts.offset ?? 0));
|
|
102
|
+
return fetchJsonWithDeadline(`${creds.apiBase}/api/cli/inventory?${params}`, {
|
|
103
|
+
headers: authFetchHeaders(creds),
|
|
104
|
+
}, {
|
|
105
|
+
timeoutMessage: 'Loading inventory timed out after 15 seconds. Check your connection and retry dayze inventory list.',
|
|
106
|
+
httpErrorMessage: (status, bodyPreview) => `Failed to list inventory (${status}): ${bodyPreview}`,
|
|
107
|
+
});
|
|
108
|
+
}
|
|
109
|
+
async function fetchAllInventory(creds, opts = {}) {
|
|
110
|
+
const all = [];
|
|
111
|
+
let offset = 0;
|
|
112
|
+
const limit = 100;
|
|
113
|
+
for (;;) {
|
|
114
|
+
const page = await fetchInventoryPage(creds, { ...opts, limit, offset });
|
|
115
|
+
all.push(...page.items);
|
|
116
|
+
if (!page.hasMore || page.items.length === 0)
|
|
117
|
+
break;
|
|
118
|
+
offset += page.items.length;
|
|
119
|
+
if (offset > 2000)
|
|
120
|
+
break;
|
|
121
|
+
}
|
|
122
|
+
return all;
|
|
123
|
+
}
|
|
124
|
+
async function fetchInventoryDetail(creds, id) {
|
|
125
|
+
const res = await fetch(`${creds.apiBase}/api/cli/inventory?id=${encodeURIComponent(id)}`, {
|
|
126
|
+
headers: authFetchHeaders(creds),
|
|
127
|
+
});
|
|
128
|
+
if (!res.ok) {
|
|
129
|
+
const text = await res.text().catch(() => '');
|
|
130
|
+
throw new Error(`Failed to load item (${res.status}): ${text.slice(0, 200)}`);
|
|
131
|
+
}
|
|
132
|
+
const json = (await res.json());
|
|
133
|
+
return json.item;
|
|
134
|
+
}
|
|
135
|
+
async function patchInventoryItem(creds, id, updates, opts = {}) {
|
|
136
|
+
const res = await fetch(`${creds.apiBase}/api/cli/inventory`, {
|
|
137
|
+
method: 'PATCH',
|
|
138
|
+
headers: { ...authFetchHeaders(creds), 'Content-Type': 'application/json' },
|
|
139
|
+
body: JSON.stringify({ id, ...updates, ...(opts.appendNotes ? { appendNotes: true } : {}) }),
|
|
140
|
+
});
|
|
141
|
+
if (!res.ok) {
|
|
142
|
+
const text = await res.text().catch(() => '');
|
|
143
|
+
throw new Error(`Failed to update (${res.status}): ${text.slice(0, 240)}`);
|
|
144
|
+
}
|
|
145
|
+
const json = (await res.json());
|
|
146
|
+
return json.item;
|
|
147
|
+
}
|
|
148
|
+
function numericField(v) {
|
|
149
|
+
if (v == null || !Number.isFinite(Number(v)))
|
|
150
|
+
return 0;
|
|
151
|
+
return Number(v);
|
|
152
|
+
}
|
|
153
|
+
/** Sort / display: prefer current (resell) value, else paid. */
|
|
154
|
+
function moneyValue(it) {
|
|
155
|
+
const v = it.current_value ?? it.purchase_price;
|
|
156
|
+
if (v == null || !Number.isFinite(Number(v)))
|
|
157
|
+
return null;
|
|
158
|
+
return Number(v);
|
|
159
|
+
}
|
|
160
|
+
function currencyOf(it) {
|
|
161
|
+
return (it.currency || 'USD').toUpperCase();
|
|
162
|
+
}
|
|
163
|
+
function formatAmount(amount, currency) {
|
|
164
|
+
return `${currency} ${amount.toFixed(2)}`;
|
|
165
|
+
}
|
|
166
|
+
function formatMoneyField(amount, currency) {
|
|
167
|
+
if (amount == null || !Number.isFinite(Number(amount)))
|
|
168
|
+
return '—';
|
|
169
|
+
return formatAmount(Number(amount), (currency || 'USD').toUpperCase());
|
|
170
|
+
}
|
|
171
|
+
/** Sum paid + est. resell (current_value) per currency — same as web Inventory metrics. */
|
|
172
|
+
export function inventoryValueTotals(items) {
|
|
173
|
+
const paid = new Map();
|
|
174
|
+
const resell = new Map();
|
|
175
|
+
let paidCount = 0;
|
|
176
|
+
let resellCount = 0;
|
|
177
|
+
for (const it of items) {
|
|
178
|
+
const cur = currencyOf(it);
|
|
179
|
+
const p = numericField(it.purchase_price);
|
|
180
|
+
const r = numericField(it.current_value);
|
|
181
|
+
if (p > 0) {
|
|
182
|
+
paid.set(cur, (paid.get(cur) || 0) + p);
|
|
183
|
+
paidCount += 1;
|
|
184
|
+
}
|
|
185
|
+
if (r > 0) {
|
|
186
|
+
resell.set(cur, (resell.get(cur) || 0) + r);
|
|
187
|
+
resellCount += 1;
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
return { paid, resell, paidCount, resellCount };
|
|
191
|
+
}
|
|
192
|
+
function formatTotalsMap(map) {
|
|
193
|
+
if (!map.size)
|
|
194
|
+
return '—';
|
|
195
|
+
return [...map.entries()]
|
|
196
|
+
.sort(([a], [b]) => a.localeCompare(b))
|
|
197
|
+
.map(([cur, amt]) => formatAmount(amt, cur))
|
|
198
|
+
.join(' · ');
|
|
199
|
+
}
|
|
200
|
+
function printValueSummary(items, indent = ' ') {
|
|
201
|
+
const { paid, resell, paidCount, resellCount } = inventoryValueTotals(items);
|
|
202
|
+
const paidLine = formatTotalsMap(paid);
|
|
203
|
+
const resellLine = formatTotalsMap(resell);
|
|
204
|
+
console.log(`${indent}${ui.c.dim('Paid')} ${paidLine}${paidCount ? ui.c.dim(` (${paidCount} priced)`) : ''}`);
|
|
205
|
+
console.log(`${indent}${ui.c.dim('Resell')} ${resellLine}${resellCount ? ui.c.dim(` (${resellCount} valued)`) : ''}`);
|
|
206
|
+
// Per-currency paper gain/loss when both sides exist
|
|
207
|
+
const deltas = [];
|
|
208
|
+
for (const cur of new Set([...paid.keys(), ...resell.keys()])) {
|
|
209
|
+
const p = paid.get(cur) || 0;
|
|
210
|
+
const r = resell.get(cur) || 0;
|
|
211
|
+
if (p <= 0 || r <= 0)
|
|
212
|
+
continue;
|
|
213
|
+
const d = r - p;
|
|
214
|
+
if (Math.abs(d) < 0.005)
|
|
215
|
+
continue;
|
|
216
|
+
const sign = d > 0 ? '+' : '';
|
|
217
|
+
deltas.push(`${sign}${formatAmount(d, cur)}`);
|
|
218
|
+
}
|
|
219
|
+
if (deltas.length) {
|
|
220
|
+
console.log(`${indent}${ui.c.dim('Δ')} ${deltas.join(' · ')}`);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
export function sortInventory(items, sort) {
|
|
224
|
+
const byName = (a, b) => (a.name || '').localeCompare(b.name || '', undefined, { sensitivity: 'base' });
|
|
225
|
+
const list = [...items];
|
|
226
|
+
switch (sort) {
|
|
227
|
+
case 'name':
|
|
228
|
+
return list.sort(byName);
|
|
229
|
+
case 'updated':
|
|
230
|
+
return list.sort((a, b) => {
|
|
231
|
+
const ta = a.updated_at ? new Date(a.updated_at).getTime() : NaN;
|
|
232
|
+
const tb = b.updated_at ? new Date(b.updated_at).getTime() : NaN;
|
|
233
|
+
const hasA = Number.isFinite(ta);
|
|
234
|
+
const hasB = Number.isFinite(tb);
|
|
235
|
+
if (hasA && hasB && ta !== tb)
|
|
236
|
+
return tb - ta;
|
|
237
|
+
if (hasA !== hasB)
|
|
238
|
+
return hasA ? -1 : 1;
|
|
239
|
+
return byName(a, b) || a.id.localeCompare(b.id);
|
|
240
|
+
});
|
|
241
|
+
case 'price-desc':
|
|
242
|
+
return list.sort((a, b) => {
|
|
243
|
+
const va = moneyValue(a);
|
|
244
|
+
const vb = moneyValue(b);
|
|
245
|
+
if (va == null && vb == null)
|
|
246
|
+
return byName(a, b);
|
|
247
|
+
if (va == null)
|
|
248
|
+
return 1;
|
|
249
|
+
if (vb == null)
|
|
250
|
+
return -1;
|
|
251
|
+
return vb - va;
|
|
252
|
+
});
|
|
253
|
+
case 'price-asc':
|
|
254
|
+
return list.sort((a, b) => {
|
|
255
|
+
const va = moneyValue(a);
|
|
256
|
+
const vb = moneyValue(b);
|
|
257
|
+
if (va == null && vb == null)
|
|
258
|
+
return byName(a, b);
|
|
259
|
+
if (va == null)
|
|
260
|
+
return 1;
|
|
261
|
+
if (vb == null)
|
|
262
|
+
return -1;
|
|
263
|
+
return va - vb;
|
|
264
|
+
});
|
|
265
|
+
case 'purchased':
|
|
266
|
+
return list.sort((a, b) => {
|
|
267
|
+
const da = a.purchase_date || '';
|
|
268
|
+
const db = b.purchase_date || '';
|
|
269
|
+
if (!da && !db)
|
|
270
|
+
return byName(a, b);
|
|
271
|
+
if (!da)
|
|
272
|
+
return 1;
|
|
273
|
+
if (!db)
|
|
274
|
+
return -1;
|
|
275
|
+
return db.localeCompare(da);
|
|
276
|
+
});
|
|
277
|
+
case 'category':
|
|
278
|
+
return list.sort((a, b) => {
|
|
279
|
+
const ca = (a.category || a.item_type || '').localeCompare(b.category || b.item_type || '', undefined, {
|
|
280
|
+
sensitivity: 'base',
|
|
281
|
+
});
|
|
282
|
+
return ca || byName(a, b);
|
|
283
|
+
});
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
function matchHaystack(it) {
|
|
287
|
+
return [
|
|
288
|
+
it.name,
|
|
289
|
+
it.brand,
|
|
290
|
+
it.item_type,
|
|
291
|
+
it.category,
|
|
292
|
+
it.color,
|
|
293
|
+
it.location,
|
|
294
|
+
it.status,
|
|
295
|
+
it.notes,
|
|
296
|
+
...(it.tags || []),
|
|
297
|
+
]
|
|
298
|
+
.filter(Boolean)
|
|
299
|
+
.join(' ')
|
|
300
|
+
.toLowerCase();
|
|
301
|
+
}
|
|
302
|
+
export function filterInventory(items, query) {
|
|
303
|
+
const q = query.trim().toLowerCase();
|
|
304
|
+
if (!q)
|
|
305
|
+
return items;
|
|
306
|
+
const tokens = q.split(/\s+/).filter(Boolean);
|
|
307
|
+
return items.filter((it) => {
|
|
308
|
+
const hay = matchHaystack(it);
|
|
309
|
+
return tokens.every((t) => hay.includes(t));
|
|
310
|
+
});
|
|
311
|
+
}
|
|
312
|
+
function pad(s, width) {
|
|
313
|
+
if (width <= 0)
|
|
314
|
+
return '';
|
|
315
|
+
if (s.length >= width) {
|
|
316
|
+
if (width === 1)
|
|
317
|
+
return '…';
|
|
318
|
+
return `${s.slice(0, Math.max(0, width - 1))}…`;
|
|
319
|
+
}
|
|
320
|
+
return s + ' '.repeat(width - s.length);
|
|
321
|
+
}
|
|
322
|
+
function listDensity() {
|
|
323
|
+
const w = process.stdout.columns || 100;
|
|
324
|
+
if (w < 56)
|
|
325
|
+
return 'phone';
|
|
326
|
+
if (w < 100)
|
|
327
|
+
return 'tablet';
|
|
328
|
+
return 'desktop';
|
|
329
|
+
}
|
|
330
|
+
function termWidth() {
|
|
331
|
+
return Math.max(28, process.stdout.columns || 80);
|
|
332
|
+
}
|
|
333
|
+
function formatMoneyCompact(amount, currency) {
|
|
334
|
+
if (amount == null || !Number.isFinite(Number(amount)))
|
|
335
|
+
return '—';
|
|
336
|
+
const cur = (currency || 'USD').toUpperCase();
|
|
337
|
+
const n = Number(amount);
|
|
338
|
+
const tag = cur.slice(0, 2);
|
|
339
|
+
if (n >= 1000)
|
|
340
|
+
return `${tag}${(n / 1000).toFixed(1)}k`;
|
|
341
|
+
return `${tag}${n.toFixed(0)}`;
|
|
342
|
+
}
|
|
343
|
+
function inventoryPhoneMeta(it, sort) {
|
|
344
|
+
if (sort === 'price-desc' || sort === 'price-asc') {
|
|
345
|
+
const v = moneyValue(it);
|
|
346
|
+
return v != null ? formatMoneyCompact(v, it.currency) : '—';
|
|
347
|
+
}
|
|
348
|
+
if (sort === 'category') {
|
|
349
|
+
const cat = (it.category || it.item_type || '—').slice(0, 6);
|
|
350
|
+
return cat;
|
|
351
|
+
}
|
|
352
|
+
if (sort === 'purchased')
|
|
353
|
+
return (it.purchase_date || '—').slice(5, 10) || '—';
|
|
354
|
+
if (sort === 'updated') {
|
|
355
|
+
if (!it.updated_at)
|
|
356
|
+
return '—';
|
|
357
|
+
const d = new Date(it.updated_at);
|
|
358
|
+
if (!Number.isFinite(d.getTime()))
|
|
359
|
+
return '—';
|
|
360
|
+
return `${d.getMonth() + 1}/${d.getDate()}`;
|
|
361
|
+
}
|
|
362
|
+
return formatMoneyCompact(it.purchase_price, it.currency);
|
|
363
|
+
}
|
|
364
|
+
function inventoryPhoneMetaHeader(sort) {
|
|
365
|
+
if (sort === 'price-desc' || sort === 'price-asc')
|
|
366
|
+
return 'VAL';
|
|
367
|
+
if (sort === 'category')
|
|
368
|
+
return 'CAT';
|
|
369
|
+
if (sort === 'purchased')
|
|
370
|
+
return 'BUY';
|
|
371
|
+
if (sort === 'updated')
|
|
372
|
+
return 'UPD';
|
|
373
|
+
return 'PAID';
|
|
374
|
+
}
|
|
375
|
+
function inventoryCols() {
|
|
376
|
+
const density = listDensity();
|
|
377
|
+
const width = termWidth();
|
|
378
|
+
if (density === 'phone') {
|
|
379
|
+
const metaW = 5;
|
|
380
|
+
const nameW = Math.max(10, width - 2 - 1 - metaW - 1);
|
|
381
|
+
return { nameW, paidW: 0, resellW: 0, metaW };
|
|
382
|
+
}
|
|
383
|
+
if (density === 'tablet') {
|
|
384
|
+
const paidW = 9;
|
|
385
|
+
const resellW = 9;
|
|
386
|
+
const nameW = Math.max(10, width - 2 - paidW - resellW - 6);
|
|
387
|
+
return { nameW, paidW, resellW, metaW: 0 };
|
|
388
|
+
}
|
|
389
|
+
const nameW = Math.min(34, Math.max(12, Math.floor(width * 0.42)));
|
|
390
|
+
return { nameW, paidW: 11, resellW: 11, metaW: 0 };
|
|
391
|
+
}
|
|
392
|
+
function formatInventoryListRow(it, selected, sort) {
|
|
393
|
+
const density = listDensity();
|
|
394
|
+
const { nameW, paidW, resellW, metaW } = inventoryCols();
|
|
395
|
+
const marker = selected ? ui.c.brandBold('❯') : ' ';
|
|
396
|
+
if (density === 'phone') {
|
|
397
|
+
const name = pad(it.name, nameW);
|
|
398
|
+
const meta = pad(inventoryPhoneMeta(it, sort), metaW);
|
|
399
|
+
const mid = `${name} ${meta}`;
|
|
400
|
+
return `${marker} ${selected ? ui.c.bold(mid) : mid}`;
|
|
401
|
+
}
|
|
402
|
+
if (density === 'tablet') {
|
|
403
|
+
const name = pad(it.name, nameW);
|
|
404
|
+
const paid = pad(formatMoneyField(it.purchase_price, it.currency), paidW);
|
|
405
|
+
const resell = pad(formatMoneyField(it.current_value, it.currency), resellW);
|
|
406
|
+
const mid = `${name} ${paid} ${resell}`;
|
|
407
|
+
return `${marker} ${selected ? ui.c.bold(mid) : mid}`;
|
|
408
|
+
}
|
|
409
|
+
const name = pad(it.name, nameW);
|
|
410
|
+
const paid = pad(formatMoneyField(it.purchase_price, it.currency), paidW);
|
|
411
|
+
const resell = pad(formatMoneyField(it.current_value, it.currency), resellW);
|
|
412
|
+
const meta = [it.brand, it.item_type || it.category].filter(Boolean).join(' · ') || '—';
|
|
413
|
+
const line = `${name} ${paid} ${resell} ${ui.c.dim(meta)}`;
|
|
414
|
+
return `${marker} ${selected ? ui.c.bold(line) : line}`;
|
|
415
|
+
}
|
|
416
|
+
function inventoryHeaderRow(sort) {
|
|
417
|
+
const density = listDensity();
|
|
418
|
+
const { nameW, paidW, resellW, metaW } = inventoryCols();
|
|
419
|
+
if (density === 'phone') {
|
|
420
|
+
return ` ${ui.c.dim(pad('NAME', nameW))} ${ui.c.dim(pad(inventoryPhoneMetaHeader(sort), metaW))}`;
|
|
421
|
+
}
|
|
422
|
+
if (density === 'tablet') {
|
|
423
|
+
return ` ${ui.c.dim(pad('NAME', nameW))} ${ui.c.dim(pad('paid', paidW))} ${ui.c.dim(pad('resell', resellW))}`;
|
|
424
|
+
}
|
|
425
|
+
return ` ${ui.c.dim(pad('', nameW))} ${ui.c.dim(pad('paid', paidW))} ${ui.c.dim(pad('resell', resellW))} ${ui.c.dim('meta')}`;
|
|
426
|
+
}
|
|
427
|
+
function compactTotalsLine(items) {
|
|
428
|
+
const { paid, resell } = inventoryValueTotals(items);
|
|
429
|
+
const parts = [];
|
|
430
|
+
for (const [cur, amt] of paid)
|
|
431
|
+
parts.push(`p ${cur}${amt.toFixed(0)}`);
|
|
432
|
+
for (const [cur, amt] of resell)
|
|
433
|
+
parts.push(`r ${cur}${amt.toFixed(0)}`);
|
|
434
|
+
if (!parts.length)
|
|
435
|
+
return '—';
|
|
436
|
+
const line = parts.join(' · ');
|
|
437
|
+
const max = Math.max(20, termWidth() - 4);
|
|
438
|
+
return line.length <= max ? line : `${line.slice(0, max - 1)}…`;
|
|
439
|
+
}
|
|
440
|
+
function formatTotalsLine(items) {
|
|
441
|
+
const { paid, resell } = inventoryValueTotals(items);
|
|
442
|
+
return `paid ${formatTotalsMap(paid)} · resell ${formatTotalsMap(resell)}`;
|
|
443
|
+
}
|
|
444
|
+
async function deleteInventoryItem(creds, id) {
|
|
445
|
+
const res = await fetch(`${creds.apiBase}/api/cli/inventory?id=${encodeURIComponent(id)}`, {
|
|
446
|
+
method: 'DELETE',
|
|
447
|
+
headers: authFetchHeaders(creds),
|
|
448
|
+
});
|
|
449
|
+
if (!res.ok) {
|
|
450
|
+
const text = await res.text().catch(() => '');
|
|
451
|
+
throw new Error(`Failed to delete (${res.status}): ${text.slice(0, 240)}`);
|
|
452
|
+
}
|
|
453
|
+
}
|
|
454
|
+
function removeFromDirectory(directory, id) {
|
|
455
|
+
const i = directory.findIndex((x) => x.id === id);
|
|
456
|
+
if (i >= 0)
|
|
457
|
+
directory.splice(i, 1);
|
|
458
|
+
}
|
|
459
|
+
function mergeIntoDirectory(directory, updated) {
|
|
460
|
+
const i = directory.findIndex((x) => x.id === updated.id);
|
|
461
|
+
if (i < 0)
|
|
462
|
+
return;
|
|
463
|
+
directory[i] = { ...directory[i], ...updated };
|
|
464
|
+
}
|
|
465
|
+
function toInventoryAgentContext(it) {
|
|
466
|
+
return {
|
|
467
|
+
id: it.id,
|
|
468
|
+
name: it.name,
|
|
469
|
+
category: it.category,
|
|
470
|
+
item_type: it.item_type,
|
|
471
|
+
brand: it.brand,
|
|
472
|
+
color: it.color,
|
|
473
|
+
size: it.size,
|
|
474
|
+
condition: it.condition,
|
|
475
|
+
status: it.status,
|
|
476
|
+
purchase_price: it.purchase_price,
|
|
477
|
+
current_value: it.current_value,
|
|
478
|
+
currency: it.currency,
|
|
479
|
+
purchase_date: it.purchase_date,
|
|
480
|
+
location: it.location,
|
|
481
|
+
tags: it.tags,
|
|
482
|
+
notes: it.notes,
|
|
483
|
+
};
|
|
484
|
+
}
|
|
485
|
+
function fieldValue(it, key) {
|
|
486
|
+
const v = it[key];
|
|
487
|
+
if (v == null)
|
|
488
|
+
return '';
|
|
489
|
+
if (Array.isArray(v))
|
|
490
|
+
return v.join(', ');
|
|
491
|
+
return String(v);
|
|
492
|
+
}
|
|
493
|
+
export function printInventoryDetail(it, footerHint = true) {
|
|
494
|
+
console.log('');
|
|
495
|
+
console.log(`${ui.c.brandBold('◆')} ${ui.c.bold(it.name)}`);
|
|
496
|
+
const meta = [it.brand, it.item_type || it.category, it.color, it.size].filter(Boolean).join(' · ');
|
|
497
|
+
if (meta)
|
|
498
|
+
console.log(` ${ui.c.dim(meta)}`);
|
|
499
|
+
console.log('');
|
|
500
|
+
const paid = formatMoneyField(it.purchase_price, it.currency);
|
|
501
|
+
const resell = formatMoneyField(it.current_value, it.currency);
|
|
502
|
+
const rows = [
|
|
503
|
+
['Status', it.status || '—'],
|
|
504
|
+
['Condition', it.condition || '—'],
|
|
505
|
+
['Paid', paid],
|
|
506
|
+
['Resell', resell],
|
|
507
|
+
['Bought', it.purchase_date || '—'],
|
|
508
|
+
['Location', it.location || '—'],
|
|
509
|
+
['Tags', (it.tags || []).join(', ') || '—'],
|
|
510
|
+
['Notes', it.notes || '—'],
|
|
511
|
+
];
|
|
512
|
+
for (const [label, val] of rows) {
|
|
513
|
+
console.log(` ${ui.c.dim(label.padEnd(10))} ${val}`);
|
|
514
|
+
}
|
|
515
|
+
console.log('');
|
|
516
|
+
if (footerHint) {
|
|
517
|
+
const del = listDensity() === 'phone' ? 'd del' : 'd delete';
|
|
518
|
+
console.log(ui.c.dim(` a agent · e edit · n note · ${del} · Esc back`));
|
|
519
|
+
console.log('');
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
function printInventoryTable(items, title, sort) {
|
|
523
|
+
const density = listDensity();
|
|
524
|
+
console.log('');
|
|
525
|
+
if (density === 'phone') {
|
|
526
|
+
console.log(`${ui.c.brandBold('◆')} ${ui.c.bold(title)} ${ui.c.dim(`${items.length}`)} ${ui.c.brand(inventorySortLabel(sort))}`);
|
|
527
|
+
}
|
|
528
|
+
else {
|
|
529
|
+
console.log(`${ui.c.brandBold('◆')} ${ui.c.bold(title)} ${ui.c.dim(`${items.length} · sort ${inventorySortLabel(sort)}`)}`);
|
|
530
|
+
}
|
|
531
|
+
if (!items.length) {
|
|
532
|
+
console.log(ui.c.dim(' (empty)'));
|
|
533
|
+
console.log('');
|
|
534
|
+
return;
|
|
535
|
+
}
|
|
536
|
+
console.log(inventoryHeaderRow(sort));
|
|
537
|
+
console.log(ui.c.dim('─'.repeat(Math.min(termWidth(), 72))));
|
|
538
|
+
for (const it of items) {
|
|
539
|
+
console.log(` ${formatInventoryListRow(it, false, sort)}`);
|
|
540
|
+
}
|
|
541
|
+
console.log('');
|
|
542
|
+
if (density === 'phone') {
|
|
543
|
+
console.log(ui.c.dim(` ${compactTotalsLine(items)}`));
|
|
544
|
+
}
|
|
545
|
+
else {
|
|
546
|
+
printValueSummary(items);
|
|
547
|
+
}
|
|
548
|
+
console.log('');
|
|
549
|
+
}
|
|
550
|
+
function resolveByQuery(items, query) {
|
|
551
|
+
const q = query.trim().toLowerCase();
|
|
552
|
+
if (!q)
|
|
553
|
+
return null;
|
|
554
|
+
const exact = items.find((i) => i.name.toLowerCase() === q);
|
|
555
|
+
if (exact)
|
|
556
|
+
return exact;
|
|
557
|
+
const starts = items.filter((i) => i.name.toLowerCase().startsWith(q));
|
|
558
|
+
if (starts.length === 1)
|
|
559
|
+
return starts[0];
|
|
560
|
+
const contains = items.filter((i) => matchHaystack(i).includes(q));
|
|
561
|
+
if (contains.length === 1)
|
|
562
|
+
return contains[0];
|
|
563
|
+
return null;
|
|
564
|
+
}
|
|
565
|
+
export async function runInventoryBrowser(creds, opts = {}) {
|
|
566
|
+
const spinner = new ui.Spinner('Loading inventory');
|
|
567
|
+
spinner.start();
|
|
568
|
+
let directory;
|
|
569
|
+
try {
|
|
570
|
+
directory = await fetchAllInventory(creds, {
|
|
571
|
+
status: opts.status || 'owned',
|
|
572
|
+
category: opts.category,
|
|
573
|
+
});
|
|
574
|
+
}
|
|
575
|
+
finally {
|
|
576
|
+
spinner.stop();
|
|
577
|
+
}
|
|
578
|
+
const initialSort = opts.sort || 'updated';
|
|
579
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
580
|
+
const sorted = sortInventory(filterInventory(directory, opts.query || ''), initialSort);
|
|
581
|
+
printInventoryTable(sorted, 'Inventory', initialSort);
|
|
582
|
+
return;
|
|
583
|
+
}
|
|
584
|
+
const { emitKeypressEvents } = await import('node:readline');
|
|
585
|
+
emitKeypressEvents(process.stdin);
|
|
586
|
+
process.stdin.setRawMode(true);
|
|
587
|
+
process.stdin.resume();
|
|
588
|
+
process.stdin.setEncoding('utf8');
|
|
589
|
+
let filter = opts.query || '';
|
|
590
|
+
let sort = initialSort;
|
|
591
|
+
let cursor = 0;
|
|
592
|
+
let scroll = 0;
|
|
593
|
+
let mode = 'list';
|
|
594
|
+
let detail = null;
|
|
595
|
+
let dirty = true;
|
|
596
|
+
let busy = false;
|
|
597
|
+
const visibleRows = () => {
|
|
598
|
+
const rows = process.stdout.rows || 24;
|
|
599
|
+
if (listDensity() === 'phone')
|
|
600
|
+
return Math.max(8, Math.min(32, rows - 5));
|
|
601
|
+
return Math.max(6, Math.min(28, rows - 6));
|
|
602
|
+
};
|
|
603
|
+
const filtered = () => sortInventory(filterInventory(directory, filter), sort);
|
|
604
|
+
const ensureVisible = () => {
|
|
605
|
+
const rows = visibleRows();
|
|
606
|
+
const list = filtered();
|
|
607
|
+
if (cursor < 0)
|
|
608
|
+
cursor = 0;
|
|
609
|
+
if (cursor >= list.length)
|
|
610
|
+
cursor = Math.max(0, list.length - 1);
|
|
611
|
+
if (cursor < scroll)
|
|
612
|
+
scroll = cursor;
|
|
613
|
+
if (cursor >= scroll + rows)
|
|
614
|
+
scroll = cursor - rows + 1;
|
|
615
|
+
if (scroll < 0)
|
|
616
|
+
scroll = 0;
|
|
617
|
+
};
|
|
618
|
+
const cleanup = () => {
|
|
619
|
+
try {
|
|
620
|
+
process.stdin.setRawMode(false);
|
|
621
|
+
}
|
|
622
|
+
catch {
|
|
623
|
+
/* ignore */
|
|
624
|
+
}
|
|
625
|
+
process.stdin.pause();
|
|
626
|
+
process.stdin.removeAllListeners('keypress');
|
|
627
|
+
process.stdout.write('\x1b[?25h');
|
|
628
|
+
};
|
|
629
|
+
const clearScreen = () => {
|
|
630
|
+
process.stdout.write('\x1b[?25l\x1b[2J\x1b[H');
|
|
631
|
+
};
|
|
632
|
+
const enterRaw = () => {
|
|
633
|
+
try {
|
|
634
|
+
process.stdin.setRawMode(true);
|
|
635
|
+
}
|
|
636
|
+
catch {
|
|
637
|
+
/* ignore */
|
|
638
|
+
}
|
|
639
|
+
process.stdin.resume();
|
|
640
|
+
process.stdout.write('\x1b[?25l');
|
|
641
|
+
};
|
|
642
|
+
const leaveRaw = () => {
|
|
643
|
+
try {
|
|
644
|
+
process.stdin.setRawMode(false);
|
|
645
|
+
}
|
|
646
|
+
catch {
|
|
647
|
+
/* ignore */
|
|
648
|
+
}
|
|
649
|
+
process.stdout.write('\x1b[?25h');
|
|
650
|
+
};
|
|
651
|
+
let keyHandler = null;
|
|
652
|
+
const pauseKeys = () => {
|
|
653
|
+
if (keyHandler)
|
|
654
|
+
process.stdin.removeListener('keypress', keyHandler);
|
|
655
|
+
leaveRaw();
|
|
656
|
+
};
|
|
657
|
+
const resumeKeys = () => {
|
|
658
|
+
enterRaw();
|
|
659
|
+
if (keyHandler)
|
|
660
|
+
process.stdin.on('keypress', keyHandler);
|
|
661
|
+
};
|
|
662
|
+
const runDetailEdit = async () => {
|
|
663
|
+
if (!detail)
|
|
664
|
+
return;
|
|
665
|
+
pauseKeys();
|
|
666
|
+
console.log('');
|
|
667
|
+
console.log(ui.c.bold(`Edit ${detail.name}`));
|
|
668
|
+
EDITABLE_FIELDS.forEach((f, i) => {
|
|
669
|
+
const cur = fieldValue(detail, f.key);
|
|
670
|
+
const preview = cur ? (cur.length > 48 ? `${cur.slice(0, 47)}…` : cur) : '—';
|
|
671
|
+
console.log(` ${ui.c.dim(String(i + 1).padStart(2))} ${f.label.padEnd(12)} ${ui.c.dim(preview)}`);
|
|
672
|
+
});
|
|
673
|
+
console.log('');
|
|
674
|
+
const pick = await promptLine('Field number (or name, blank cancel): ');
|
|
675
|
+
if (!pick) {
|
|
676
|
+
resumeKeys();
|
|
677
|
+
dirty = true;
|
|
678
|
+
render();
|
|
679
|
+
return;
|
|
680
|
+
}
|
|
681
|
+
const byNum = /^\d+$/.test(pick) ? EDITABLE_FIELDS[parseInt(pick, 10) - 1] : undefined;
|
|
682
|
+
const byName = EDITABLE_FIELDS.find((f) => f.key === pick.toLowerCase() || f.label.toLowerCase() === pick.toLowerCase());
|
|
683
|
+
const field = byNum || byName;
|
|
684
|
+
if (!field) {
|
|
685
|
+
ui.err(`Unknown field “${pick}”`);
|
|
686
|
+
resumeKeys();
|
|
687
|
+
dirty = true;
|
|
688
|
+
render();
|
|
689
|
+
return;
|
|
690
|
+
}
|
|
691
|
+
const current = fieldValue(detail, field.key);
|
|
692
|
+
console.log(ui.c.dim(`Current ${field.label}: ${current || '(empty)'}`));
|
|
693
|
+
const next = await promptLine(`New ${field.label} (empty clears, . keeps): `);
|
|
694
|
+
if (next === '.') {
|
|
695
|
+
resumeKeys();
|
|
696
|
+
dirty = true;
|
|
697
|
+
render();
|
|
698
|
+
return;
|
|
699
|
+
}
|
|
700
|
+
try {
|
|
701
|
+
let value = next === '' ? null : next;
|
|
702
|
+
if ((field.key === 'purchase_price' || field.key === 'current_value') && next !== '') {
|
|
703
|
+
const n = Number(next);
|
|
704
|
+
if (!Number.isFinite(n)) {
|
|
705
|
+
ui.err('Enter a number');
|
|
706
|
+
resumeKeys();
|
|
707
|
+
dirty = true;
|
|
708
|
+
render();
|
|
709
|
+
return;
|
|
710
|
+
}
|
|
711
|
+
value = n;
|
|
712
|
+
}
|
|
713
|
+
detail = await patchInventoryItem(creds, detail.id, { [field.key]: value });
|
|
714
|
+
mergeIntoDirectory(directory, detail);
|
|
715
|
+
ui.ok(`Updated ${field.label}`);
|
|
716
|
+
}
|
|
717
|
+
catch (err) {
|
|
718
|
+
ui.err(err instanceof Error ? err.message : String(err));
|
|
719
|
+
}
|
|
720
|
+
resumeKeys();
|
|
721
|
+
dirty = true;
|
|
722
|
+
render();
|
|
723
|
+
};
|
|
724
|
+
const runDetailNote = async () => {
|
|
725
|
+
if (!detail)
|
|
726
|
+
return;
|
|
727
|
+
pauseKeys();
|
|
728
|
+
console.log('');
|
|
729
|
+
const note = await promptLine(`Append note for ${detail.name}: `);
|
|
730
|
+
if (!note) {
|
|
731
|
+
resumeKeys();
|
|
732
|
+
dirty = true;
|
|
733
|
+
render();
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
try {
|
|
737
|
+
detail = await patchInventoryItem(creds, detail.id, { notes: note }, { appendNotes: true });
|
|
738
|
+
mergeIntoDirectory(directory, detail);
|
|
739
|
+
ui.ok('Note saved');
|
|
740
|
+
}
|
|
741
|
+
catch (err) {
|
|
742
|
+
ui.err(err instanceof Error ? err.message : String(err));
|
|
743
|
+
}
|
|
744
|
+
resumeKeys();
|
|
745
|
+
dirty = true;
|
|
746
|
+
render();
|
|
747
|
+
};
|
|
748
|
+
const runDetailAgent = async () => {
|
|
749
|
+
if (!detail)
|
|
750
|
+
return;
|
|
751
|
+
const itemId = detail.id;
|
|
752
|
+
pauseKeys();
|
|
753
|
+
console.log('');
|
|
754
|
+
console.log(ui.c.dim(`Dayze agent for ${detail.name} · e.g. “set price to 50 SGD”, “mark as sold”, “add note that …”`));
|
|
755
|
+
const instruction = await promptLine(ui.promptLabel());
|
|
756
|
+
if (!instruction) {
|
|
757
|
+
resumeKeys();
|
|
758
|
+
dirty = true;
|
|
759
|
+
render();
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const agentSpinner = new ui.Spinner('Dayze');
|
|
763
|
+
agentSpinner.start();
|
|
764
|
+
let printedHeader = false;
|
|
765
|
+
let startedReply = false;
|
|
766
|
+
let replyText = '';
|
|
767
|
+
let didUpdate = false;
|
|
768
|
+
try {
|
|
769
|
+
const inventoryContext = toInventoryAgentContext(detail);
|
|
770
|
+
const result = await askAgent(creds, instruction, [], undefined, {
|
|
771
|
+
onThinking: (step) => {
|
|
772
|
+
agentSpinner.stop();
|
|
773
|
+
ui.thinking(step);
|
|
774
|
+
},
|
|
775
|
+
onToolCall: (tool, d) => {
|
|
776
|
+
agentSpinner.stop();
|
|
777
|
+
ui.toolCall(tool, d);
|
|
778
|
+
},
|
|
779
|
+
onToolResult: (tool, d) => {
|
|
780
|
+
agentSpinner.stop();
|
|
781
|
+
ui.toolDone(tool, d);
|
|
782
|
+
},
|
|
783
|
+
onFirstText: () => {
|
|
784
|
+
agentSpinner.stop();
|
|
785
|
+
if (!printedHeader) {
|
|
786
|
+
printedHeader = true;
|
|
787
|
+
process.stdout.write(`${ui.agentLabel()}\n`);
|
|
788
|
+
}
|
|
789
|
+
startedReply = true;
|
|
790
|
+
},
|
|
791
|
+
onText: (chunk) => {
|
|
792
|
+
if (!startedReply) {
|
|
793
|
+
agentSpinner.stop();
|
|
794
|
+
if (!printedHeader) {
|
|
795
|
+
printedHeader = true;
|
|
796
|
+
process.stdout.write(`${ui.agentLabel()}\n`);
|
|
797
|
+
}
|
|
798
|
+
startedReply = true;
|
|
799
|
+
}
|
|
800
|
+
process.stdout.write(chunk);
|
|
801
|
+
},
|
|
802
|
+
}, {
|
|
803
|
+
inventoryContext,
|
|
804
|
+
pageContext: {
|
|
805
|
+
path: `/inventory/${itemId}`,
|
|
806
|
+
pathname: `/inventory/${itemId}`,
|
|
807
|
+
surface: 'dayze_cli_inventory',
|
|
808
|
+
client: 'dayze-cli',
|
|
809
|
+
area: 'inventory',
|
|
810
|
+
},
|
|
811
|
+
});
|
|
812
|
+
agentSpinner.stop();
|
|
813
|
+
replyText = result.reply;
|
|
814
|
+
if (startedReply)
|
|
815
|
+
process.stdout.write('\n');
|
|
816
|
+
else
|
|
817
|
+
console.log(`${ui.agentLabel()}\n${result.reply}\n`);
|
|
818
|
+
didUpdate = result.toolsUsed.includes('update_inventory_item');
|
|
819
|
+
if (didUpdate)
|
|
820
|
+
await new Promise((r) => setTimeout(r, 200));
|
|
821
|
+
detail = await fetchInventoryDetail(creds, itemId);
|
|
822
|
+
mergeIntoDirectory(directory, detail);
|
|
823
|
+
}
|
|
824
|
+
catch (err) {
|
|
825
|
+
agentSpinner.stop();
|
|
826
|
+
ui.err(err instanceof Error ? err.message : String(err));
|
|
827
|
+
try {
|
|
828
|
+
detail = await fetchInventoryDetail(creds, itemId);
|
|
829
|
+
mergeIntoDirectory(directory, detail);
|
|
830
|
+
}
|
|
831
|
+
catch {
|
|
832
|
+
/* keep prior */
|
|
833
|
+
}
|
|
834
|
+
}
|
|
835
|
+
resumeKeys();
|
|
836
|
+
clearScreen();
|
|
837
|
+
dirty = false;
|
|
838
|
+
if (detail) {
|
|
839
|
+
printInventoryDetail(detail);
|
|
840
|
+
if (didUpdate)
|
|
841
|
+
ui.ok('Item updated');
|
|
842
|
+
else if (replyText)
|
|
843
|
+
console.log(ui.c.dim(' (no inventory fields changed)'));
|
|
844
|
+
console.log('');
|
|
845
|
+
}
|
|
846
|
+
else {
|
|
847
|
+
dirty = true;
|
|
848
|
+
render();
|
|
849
|
+
}
|
|
850
|
+
};
|
|
851
|
+
const runDetailDelete = async () => {
|
|
852
|
+
if (!detail)
|
|
853
|
+
return;
|
|
854
|
+
const item = detail;
|
|
855
|
+
pauseKeys();
|
|
856
|
+
console.log('');
|
|
857
|
+
console.log(ui.c.yellow(`Delete “${item.name}”? This cannot be undone.`));
|
|
858
|
+
const confirm = await promptLine('Type the item name to confirm (blank cancel): ');
|
|
859
|
+
if (confirm.trim().toLowerCase() !== item.name.trim().toLowerCase()) {
|
|
860
|
+
if (confirm.trim())
|
|
861
|
+
ui.err('Name did not match — cancelled');
|
|
862
|
+
resumeKeys();
|
|
863
|
+
dirty = true;
|
|
864
|
+
render();
|
|
865
|
+
return;
|
|
866
|
+
}
|
|
867
|
+
try {
|
|
868
|
+
await deleteInventoryItem(creds, item.id);
|
|
869
|
+
removeFromDirectory(directory, item.id);
|
|
870
|
+
ui.ok(`Deleted “${item.name}”`);
|
|
871
|
+
mode = 'list';
|
|
872
|
+
detail = null;
|
|
873
|
+
const list = filtered();
|
|
874
|
+
cursor = Math.min(cursor, Math.max(0, list.length - 1));
|
|
875
|
+
}
|
|
876
|
+
catch (err) {
|
|
877
|
+
ui.err(err instanceof Error ? err.message : String(err));
|
|
878
|
+
}
|
|
879
|
+
resumeKeys();
|
|
880
|
+
dirty = true;
|
|
881
|
+
render();
|
|
882
|
+
};
|
|
883
|
+
const render = () => {
|
|
884
|
+
if (!dirty)
|
|
885
|
+
return;
|
|
886
|
+
dirty = false;
|
|
887
|
+
clearScreen();
|
|
888
|
+
if (mode === 'detail' && detail) {
|
|
889
|
+
printInventoryDetail(detail);
|
|
890
|
+
return;
|
|
891
|
+
}
|
|
892
|
+
ensureVisible();
|
|
893
|
+
const list = filtered();
|
|
894
|
+
const rows = visibleRows();
|
|
895
|
+
const slice = list.slice(scroll, scroll + rows);
|
|
896
|
+
const phone = listDensity() === 'phone';
|
|
897
|
+
if (phone) {
|
|
898
|
+
console.log(`${ui.c.brandBold('◆ Inventory')} ${ui.c.dim(`${list.length}`)} ${ui.c.brand(inventorySortLabel(sort))}`);
|
|
899
|
+
console.log(`${ui.c.brand('/')}${filter}${ui.c.dim('▌')}`);
|
|
900
|
+
console.log(ui.c.dim(` ${compactTotalsLine(list)}`));
|
|
901
|
+
}
|
|
902
|
+
else {
|
|
903
|
+
console.log(`${ui.c.brandBold('◆ Inventory')} ${ui.c.dim(`${list.length}/${directory.length} · ${inventorySortLabel(sort)} · Ctrl+S sort`)}`);
|
|
904
|
+
console.log(ui.c.dim(filter ? `filter: ${filter}` : 'type to filter · ↑↓ Enter · Esc quit'));
|
|
905
|
+
console.log(ui.c.dim(formatTotalsLine(list)));
|
|
906
|
+
}
|
|
907
|
+
console.log('');
|
|
908
|
+
if (!slice.length) {
|
|
909
|
+
console.log(ui.c.dim(' (no matches)'));
|
|
910
|
+
}
|
|
911
|
+
else {
|
|
912
|
+
if (!phone)
|
|
913
|
+
console.log(inventoryHeaderRow(sort));
|
|
914
|
+
if (!phone)
|
|
915
|
+
console.log(ui.c.dim('─'.repeat(Math.min(termWidth(), 72))));
|
|
916
|
+
for (let i = 0; i < slice.length; i++) {
|
|
917
|
+
console.log(formatInventoryListRow(slice[i], scroll + i === cursor, sort));
|
|
918
|
+
}
|
|
919
|
+
}
|
|
920
|
+
const pos = list.length ? `${cursor + 1}/${list.length}` : '0/0';
|
|
921
|
+
console.log('');
|
|
922
|
+
console.log(ui.c.dim(phone
|
|
923
|
+
? ` ${pos} · type · ↑↓ · Ctrl+S · Enter · Esc`
|
|
924
|
+
: ` ${pos} · type · ↑↓ · Ctrl+S · Enter detail · Esc`));
|
|
925
|
+
};
|
|
926
|
+
const moveBy = (n) => {
|
|
927
|
+
const list = filtered();
|
|
928
|
+
if (!list.length)
|
|
929
|
+
return;
|
|
930
|
+
cursor = Math.max(0, Math.min(list.length - 1, cursor + n));
|
|
931
|
+
dirty = true;
|
|
932
|
+
render();
|
|
933
|
+
};
|
|
934
|
+
await new Promise((resolve) => {
|
|
935
|
+
keyHandler = async (ch, keyRaw) => {
|
|
936
|
+
const key = keyRaw;
|
|
937
|
+
if (busy)
|
|
938
|
+
return;
|
|
939
|
+
if (key.ctrl && key.name === 'c') {
|
|
940
|
+
cleanup();
|
|
941
|
+
console.log('');
|
|
942
|
+
resolve();
|
|
943
|
+
return;
|
|
944
|
+
}
|
|
945
|
+
if (mode === 'detail') {
|
|
946
|
+
if (key.name === 'escape' || key.name === 'left' || key.name === 'return') {
|
|
947
|
+
mode = 'list';
|
|
948
|
+
detail = null;
|
|
949
|
+
dirty = true;
|
|
950
|
+
render();
|
|
951
|
+
return;
|
|
952
|
+
}
|
|
953
|
+
if (ch === 'a' || ch === '/' || ch === 'A') {
|
|
954
|
+
busy = true;
|
|
955
|
+
try {
|
|
956
|
+
await runDetailAgent();
|
|
957
|
+
}
|
|
958
|
+
finally {
|
|
959
|
+
busy = false;
|
|
960
|
+
}
|
|
961
|
+
return;
|
|
962
|
+
}
|
|
963
|
+
if (ch === 'e' || ch === 'E') {
|
|
964
|
+
busy = true;
|
|
965
|
+
try {
|
|
966
|
+
await runDetailEdit();
|
|
967
|
+
}
|
|
968
|
+
finally {
|
|
969
|
+
busy = false;
|
|
970
|
+
}
|
|
971
|
+
return;
|
|
972
|
+
}
|
|
973
|
+
if (ch === 'n' || ch === 'N') {
|
|
974
|
+
busy = true;
|
|
975
|
+
try {
|
|
976
|
+
await runDetailNote();
|
|
977
|
+
}
|
|
978
|
+
finally {
|
|
979
|
+
busy = false;
|
|
980
|
+
}
|
|
981
|
+
return;
|
|
982
|
+
}
|
|
983
|
+
if (ch === 'd' || ch === 'D') {
|
|
984
|
+
busy = true;
|
|
985
|
+
try {
|
|
986
|
+
await runDetailDelete();
|
|
987
|
+
}
|
|
988
|
+
finally {
|
|
989
|
+
busy = false;
|
|
990
|
+
}
|
|
991
|
+
return;
|
|
992
|
+
}
|
|
993
|
+
return;
|
|
994
|
+
}
|
|
995
|
+
if (key.name === 'escape') {
|
|
996
|
+
if (filter) {
|
|
997
|
+
filter = '';
|
|
998
|
+
cursor = 0;
|
|
999
|
+
scroll = 0;
|
|
1000
|
+
dirty = true;
|
|
1001
|
+
render();
|
|
1002
|
+
}
|
|
1003
|
+
else {
|
|
1004
|
+
cleanup();
|
|
1005
|
+
console.log('');
|
|
1006
|
+
resolve();
|
|
1007
|
+
}
|
|
1008
|
+
return;
|
|
1009
|
+
}
|
|
1010
|
+
if (key.name === 'return') {
|
|
1011
|
+
const list = filtered();
|
|
1012
|
+
const selected = list[cursor];
|
|
1013
|
+
if (!selected)
|
|
1014
|
+
return;
|
|
1015
|
+
busy = true;
|
|
1016
|
+
try {
|
|
1017
|
+
detail = await fetchInventoryDetail(creds, selected.id);
|
|
1018
|
+
mode = 'detail';
|
|
1019
|
+
dirty = true;
|
|
1020
|
+
render();
|
|
1021
|
+
}
|
|
1022
|
+
catch (err) {
|
|
1023
|
+
cleanup();
|
|
1024
|
+
ui.err(err instanceof Error ? err.message : String(err));
|
|
1025
|
+
resolve();
|
|
1026
|
+
}
|
|
1027
|
+
finally {
|
|
1028
|
+
busy = false;
|
|
1029
|
+
}
|
|
1030
|
+
return;
|
|
1031
|
+
}
|
|
1032
|
+
if (key.name === 'down' || (key.ctrl && key.name === 'n')) {
|
|
1033
|
+
moveBy(1);
|
|
1034
|
+
return;
|
|
1035
|
+
}
|
|
1036
|
+
if (key.name === 'up' || (key.ctrl && key.name === 'p')) {
|
|
1037
|
+
moveBy(-1);
|
|
1038
|
+
return;
|
|
1039
|
+
}
|
|
1040
|
+
if (key.shift && key.name === 'down') {
|
|
1041
|
+
moveBy(10);
|
|
1042
|
+
return;
|
|
1043
|
+
}
|
|
1044
|
+
if (key.shift && key.name === 'up') {
|
|
1045
|
+
moveBy(-10);
|
|
1046
|
+
return;
|
|
1047
|
+
}
|
|
1048
|
+
if (key.name === 'pagedown') {
|
|
1049
|
+
moveBy(visibleRows());
|
|
1050
|
+
return;
|
|
1051
|
+
}
|
|
1052
|
+
if (key.name === 'pageup') {
|
|
1053
|
+
moveBy(-visibleRows());
|
|
1054
|
+
return;
|
|
1055
|
+
}
|
|
1056
|
+
if (key.name === 'home') {
|
|
1057
|
+
cursor = 0;
|
|
1058
|
+
scroll = 0;
|
|
1059
|
+
dirty = true;
|
|
1060
|
+
render();
|
|
1061
|
+
return;
|
|
1062
|
+
}
|
|
1063
|
+
if (key.name === 'end') {
|
|
1064
|
+
cursor = Math.max(0, filtered().length - 1);
|
|
1065
|
+
dirty = true;
|
|
1066
|
+
render();
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
if (key.name === 'backspace') {
|
|
1070
|
+
if (filter.length) {
|
|
1071
|
+
filter = filter.slice(0, -1);
|
|
1072
|
+
cursor = 0;
|
|
1073
|
+
scroll = 0;
|
|
1074
|
+
dirty = true;
|
|
1075
|
+
render();
|
|
1076
|
+
}
|
|
1077
|
+
return;
|
|
1078
|
+
}
|
|
1079
|
+
if (key.ctrl && key.name === 'l') {
|
|
1080
|
+
filter = '';
|
|
1081
|
+
cursor = 0;
|
|
1082
|
+
scroll = 0;
|
|
1083
|
+
dirty = true;
|
|
1084
|
+
render();
|
|
1085
|
+
return;
|
|
1086
|
+
}
|
|
1087
|
+
if (key.ctrl && key.name === 's') {
|
|
1088
|
+
const i = INVENTORY_SORT_CYCLE.indexOf(sort);
|
|
1089
|
+
sort = INVENTORY_SORT_CYCLE[(i + 1) % INVENTORY_SORT_CYCLE.length];
|
|
1090
|
+
cursor = 0;
|
|
1091
|
+
scroll = 0;
|
|
1092
|
+
dirty = true;
|
|
1093
|
+
render();
|
|
1094
|
+
return;
|
|
1095
|
+
}
|
|
1096
|
+
if (key.ctrl || key.meta)
|
|
1097
|
+
return;
|
|
1098
|
+
if (ch && ch.length === 1 && ch >= ' ') {
|
|
1099
|
+
filter += ch;
|
|
1100
|
+
cursor = 0;
|
|
1101
|
+
scroll = 0;
|
|
1102
|
+
dirty = true;
|
|
1103
|
+
render();
|
|
1104
|
+
}
|
|
1105
|
+
};
|
|
1106
|
+
process.stdin.on('keypress', keyHandler);
|
|
1107
|
+
render();
|
|
1108
|
+
});
|
|
1109
|
+
}
|
|
1110
|
+
export function printInventoryHelp() {
|
|
1111
|
+
console.log(`
|
|
1112
|
+
${ui.c.brandBold('dayze inventory')} ${ui.c.dim('— Life Inventory / Closet (people-style)')}
|
|
1113
|
+
|
|
1114
|
+
dayze inventory
|
|
1115
|
+
dayze inventory list [--sort=price|name|updated|bought|category]
|
|
1116
|
+
dayze inventory list --category=electronics
|
|
1117
|
+
dayze inventory add "Travel bag" --category=bags --purchase-price=80 --currency=SGD
|
|
1118
|
+
Options: ${INVENTORY_ADD_FIELDS.map(field => `--${field}`).join(', ')}
|
|
1119
|
+
Use --flag=value or --flag value. --json prints the created item.
|
|
1120
|
+
dayze inventory show "Aklief"
|
|
1121
|
+
dayze inventory delete "Handheld vacuum"
|
|
1122
|
+
dayze inventory help
|
|
1123
|
+
|
|
1124
|
+
Interactive (TTY):
|
|
1125
|
+
type to filter · ↑↓ Enter detail · Ctrl+S cycle sort
|
|
1126
|
+
Detail: a agent · e edit · n note · d delete · Esc back
|
|
1127
|
+
|
|
1128
|
+
Sorts: updated · name · price↓ · price↑ · bought · category
|
|
1129
|
+
Also: dayze ask "check my inventory" → list_inventory_items
|
|
1130
|
+
`.trimEnd());
|
|
1131
|
+
}
|
|
1132
|
+
export async function runInventoryCommand(creds, positional, options = {}) {
|
|
1133
|
+
const json = Boolean(options.json);
|
|
1134
|
+
const [head, ...rest] = positional;
|
|
1135
|
+
if (head === 'help' || head === '--help' || head === '-h') {
|
|
1136
|
+
printInventoryHelp();
|
|
1137
|
+
return;
|
|
1138
|
+
}
|
|
1139
|
+
if (head === 'add') {
|
|
1140
|
+
const body = parseAddArgs(rest, INVENTORY_ADD_FIELDS);
|
|
1141
|
+
const { item } = await postAdd(creds, 'inventory', body);
|
|
1142
|
+
if (json)
|
|
1143
|
+
printJson(item);
|
|
1144
|
+
else
|
|
1145
|
+
ui.ok(`Added “${item.name}” (${item.id})`);
|
|
1146
|
+
return;
|
|
1147
|
+
}
|
|
1148
|
+
const peel = (args) => {
|
|
1149
|
+
const take = (name) => {
|
|
1150
|
+
const eq = args.find((a) => a.startsWith(`--${name}=`));
|
|
1151
|
+
if (eq)
|
|
1152
|
+
return eq.split('=')[1];
|
|
1153
|
+
const idx = args.indexOf(`--${name}`);
|
|
1154
|
+
if (idx >= 0)
|
|
1155
|
+
return args[idx + 1];
|
|
1156
|
+
return undefined;
|
|
1157
|
+
};
|
|
1158
|
+
const sort = parseInventorySort(take('sort')) || undefined;
|
|
1159
|
+
const category = take('category');
|
|
1160
|
+
const status = take('status');
|
|
1161
|
+
const q = args
|
|
1162
|
+
.filter((a, i) => {
|
|
1163
|
+
if (a.startsWith('--'))
|
|
1164
|
+
return false;
|
|
1165
|
+
if (args[i - 1] === '--sort' || args[i - 1] === '--category' || args[i - 1] === '--status') {
|
|
1166
|
+
return false;
|
|
1167
|
+
}
|
|
1168
|
+
return true;
|
|
1169
|
+
})
|
|
1170
|
+
.join(' ')
|
|
1171
|
+
.trim() || undefined;
|
|
1172
|
+
return { sort, category, status, q };
|
|
1173
|
+
};
|
|
1174
|
+
if (!head || head === 'browse') {
|
|
1175
|
+
const { sort, category, status, q } = peel(rest);
|
|
1176
|
+
if (json) {
|
|
1177
|
+
const items = await fetchAllInventory(creds, {
|
|
1178
|
+
status: status || 'owned',
|
|
1179
|
+
category,
|
|
1180
|
+
});
|
|
1181
|
+
printJson(sortInventory(filterInventory(items, q || ''), sort || 'updated'));
|
|
1182
|
+
return;
|
|
1183
|
+
}
|
|
1184
|
+
await runInventoryBrowser(creds, { query: q, sort, category, status });
|
|
1185
|
+
return;
|
|
1186
|
+
}
|
|
1187
|
+
if (head === 'list' || head === 'ls') {
|
|
1188
|
+
const { sort, category, status, q } = peel(rest);
|
|
1189
|
+
const spinner = new ui.Spinner('Loading inventory');
|
|
1190
|
+
if (!json)
|
|
1191
|
+
spinner.start();
|
|
1192
|
+
try {
|
|
1193
|
+
const items = await fetchAllInventory(creds, {
|
|
1194
|
+
status: status || 'owned',
|
|
1195
|
+
category,
|
|
1196
|
+
});
|
|
1197
|
+
spinner.stop();
|
|
1198
|
+
const sorted = sortInventory(filterInventory(items, q || ''), sort || 'updated');
|
|
1199
|
+
if (json) {
|
|
1200
|
+
printJson(sorted);
|
|
1201
|
+
return;
|
|
1202
|
+
}
|
|
1203
|
+
printInventoryTable(sorted, 'Inventory', sort || 'updated');
|
|
1204
|
+
}
|
|
1205
|
+
catch (err) {
|
|
1206
|
+
spinner.stop();
|
|
1207
|
+
throw err;
|
|
1208
|
+
}
|
|
1209
|
+
return;
|
|
1210
|
+
}
|
|
1211
|
+
if (head === 'show' || head === 'get' || head === 'view') {
|
|
1212
|
+
const q = rest.join(' ').trim();
|
|
1213
|
+
if (!q) {
|
|
1214
|
+
ui.err('Usage: dayze inventory show "item name"');
|
|
1215
|
+
return;
|
|
1216
|
+
}
|
|
1217
|
+
const spinner = new ui.Spinner('Loading');
|
|
1218
|
+
spinner.start();
|
|
1219
|
+
try {
|
|
1220
|
+
const items = await fetchAllInventory(creds, { status: 'all' });
|
|
1221
|
+
spinner.stop();
|
|
1222
|
+
const found = resolveByQuery(items, q) || filterInventory(items, q)[0];
|
|
1223
|
+
if (!found) {
|
|
1224
|
+
ui.err(`No item matched “${q}”`);
|
|
1225
|
+
return;
|
|
1226
|
+
}
|
|
1227
|
+
const detail = await fetchInventoryDetail(creds, found.id);
|
|
1228
|
+
printInventoryDetail(detail, false);
|
|
1229
|
+
}
|
|
1230
|
+
catch (err) {
|
|
1231
|
+
spinner.stop();
|
|
1232
|
+
throw err;
|
|
1233
|
+
}
|
|
1234
|
+
return;
|
|
1235
|
+
}
|
|
1236
|
+
if (head === 'delete' || head === 'rm' || head === 'remove') {
|
|
1237
|
+
const q = rest.join(' ').trim();
|
|
1238
|
+
if (!q) {
|
|
1239
|
+
ui.err('Usage: dayze inventory delete "item name"');
|
|
1240
|
+
return;
|
|
1241
|
+
}
|
|
1242
|
+
const spinner = new ui.Spinner('Loading');
|
|
1243
|
+
spinner.start();
|
|
1244
|
+
try {
|
|
1245
|
+
const items = await fetchAllInventory(creds, { status: 'all' });
|
|
1246
|
+
spinner.stop();
|
|
1247
|
+
const found = resolveByQuery(items, q) || filterInventory(items, q)[0];
|
|
1248
|
+
if (!found) {
|
|
1249
|
+
ui.err(`No item matched “${q}”`);
|
|
1250
|
+
return;
|
|
1251
|
+
}
|
|
1252
|
+
if (process.stdin.isTTY) {
|
|
1253
|
+
console.log(ui.c.yellow(`Delete “${found.name}”? Type the name to confirm.`));
|
|
1254
|
+
const confirm = await promptLine('Confirm: ');
|
|
1255
|
+
if (confirm.trim().toLowerCase() !== found.name.trim().toLowerCase()) {
|
|
1256
|
+
ui.err('Cancelled');
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
await deleteInventoryItem(creds, found.id);
|
|
1261
|
+
ui.ok(`Deleted “${found.name}”`);
|
|
1262
|
+
}
|
|
1263
|
+
catch (err) {
|
|
1264
|
+
spinner.stop();
|
|
1265
|
+
throw err;
|
|
1266
|
+
}
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
// Default: treat positional as browse filter
|
|
1270
|
+
const { sort, category, status, q } = peel(positional);
|
|
1271
|
+
await runInventoryBrowser(creds, { query: q, sort, category, status });
|
|
1272
|
+
}
|