wetaca-cli 0.2.0 → 0.2.2

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 (4) hide show
  1. package/docs/GUIA.md +118 -118
  2. package/package.json +7 -3
  3. package/src/commands.js +700 -700
  4. package/src/lib.js +371 -371
package/src/commands.js CHANGED
@@ -1,700 +1,700 @@
1
- // wetaca-cli command implementations.
2
- import readline from 'node:readline/promises';
3
- import child_process from 'node:child_process';
4
- import fs from 'node:fs';
5
- import {
6
- CliError, usageError, EXIT, gql, cents, fmtDate, emit,
7
- getToken, loadConfig, saveConfig, saveProfile, configPath, configDir,
8
- loadCreds, saveCreds, credentialsPath, sessionRefresh,
9
- } from './lib.js';
10
- import * as Q from './queries.js';
11
-
12
- // ---------- helpers ----------
13
-
14
- // Extrae la cookie refresh-token de wetaca.com de un export del navegador.
15
- // Formatos aceptados: Netscape cookies.txt, JSON de
16
- // Cookie-Editor/EditThisCookie (array o {url, cookies}), lista de cookies DevTools,
17
- // cabecera "Cookie: ..." o el valor pelado.
18
- export function extractRefreshToken(text) {
19
- const t = String(text || '').trim();
20
- if (!t) return null;
21
- // JSON: array de cookies o {url, cookies}
22
- if (t.startsWith('[') || t.startsWith('{')) {
23
- try {
24
- const j = JSON.parse(t);
25
- const list = Array.isArray(j) ? j : (Array.isArray(j.cookies) ? j.cookies : null);
26
- if (list) {
27
- const c = list.find((x) => x && /(^|\.)wetaca\.com$/i.test(String(x.domain || ''))
28
- && x.name === 'refresh-token');
29
- return c?.value ? String(c.value) : null;
30
- }
31
- } catch { /* no era JSON, seguimos */ }
32
- }
33
- // Netscape cookies.txt: domain \t flag \t path \t secure \t expiry \t name \t value
34
- // (httpOnly cookies carry the "#HttpOnly_" prefix on the line)
35
- const lines = t.split(/\r?\n/);
36
- for (const raw of lines) {
37
- if (!raw) continue;
38
- const line = raw.startsWith('#HttpOnly_') ? raw.slice('#HttpOnly_'.length) : raw;
39
- if (line.startsWith('#')) continue;
40
- const parts = line.split('\t');
41
- if (parts.length >= 7 && /(^|\.)wetaca\.com$/i.test(parts[0]) && parts[5] === 'refresh-token') {
42
- return parts[6] || null;
43
- }
44
- }
45
- // Cabecera "Cookie: name=value; name=value" o pares sueltos
46
- const m = t.match(/(?:^|[\s;])refresh-token=([^;\s"']+)/);
47
- if (m) return m[1];
48
- // Bare value (a single line with no tabs and no ';'); an "=" can be base64 padding
49
- if (lines.length === 1 && !t.includes('\t') && !t.includes(';')) {
50
- const eq = t.indexOf('=');
51
- if (eq === -1) return t;
52
- const name = t.slice(0, eq);
53
- // si lo que hay antes del "=" es el nombre de una cookie conocida, no es un valor pelado
54
- const KNOWN = ['refresh-token', 'auth-token', 'customer-token', 'token-voucher-pending'];
55
- return KNOWN.includes(name) ? null : t;
56
- }
57
- return null;
58
- }
59
-
60
- async function confirm(flags, summary) {
61
- if (flags.yes) return;
62
- if (flags.noInput || !process.stdin.isTTY) {
63
- throw usageError(
64
- `Real-effect operation; confirmation required. Summary: ${summary}\n` +
65
- 'No terminal: repeat with --yes to confirm.',
66
- { reason: 'confirmation_required', suggested_commands: ['repeat the command with --yes'] });
67
- }
68
- const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
69
- const ans = (await rl.question(`\n${summary}\nConfirm? [y/N] `)).trim().toLowerCase();
70
- rl.close();
71
- if (ans !== 'y' && ans !== 'yes' && ans !== 's' && ans !== 'si') {
72
- throw usageError('Cancelled by the user.', { reason: 'declined' });
73
- }
74
- }
75
-
76
- function requireId(v, what) {
77
- if (!v) throw usageError(`Missing <${what}>.`);
78
- return v;
79
- }
80
-
81
- async function nextSuggestionId(profile, debug) {
82
- const d = await gql(`query nextSuggestionId { nextSuggestion { id } }`, {}, { profile, debug });
83
- if (!d.nextSuggestion?.id) {
84
- throw new CliError(EXIT.NOT_FOUND, 'No active suggestion for next week.', { reason: 'no_suggestion' });
85
- }
86
- return d.nextSuggestion.id;
87
- }
88
-
89
- // ---------- auth ----------
90
-
91
- // Pregunta por terminal; hidden=true lee en modo raw (sin eco, como sudo)
92
- function ask(question, { hidden = false } = {}) {
93
- return new Promise((resolve) => {
94
- if (!hidden) {
95
- // API de promesas (readline/promises): question() devuelve Promise, no acepta callback
96
- const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
97
- rl.question(question).then((a) => { rl.close(); resolve(a.trim()); });
98
- return;
99
- }
100
- const stdin = process.stdin;
101
- process.stderr.write(question);
102
- const wasRaw = stdin.isRaw;
103
- stdin.setRawMode(true);
104
- stdin.resume(); // mantiene vivo el loop tras cerrar el readline del email
105
- let buf = '';
106
- const onData = (chunk) => {
107
- for (const ch of String(chunk)) {
108
- if (ch === '\r' || ch === '\n') {
109
- stdin.setRawMode(wasRaw);
110
- stdin.pause();
111
- stdin.removeListener('data', onData);
112
- process.stderr.write('\n');
113
- resolve(buf.trim());
114
- return;
115
- } else if (ch === '\u0003') { // Ctrl+C
116
- stdin.setRawMode(wasRaw);
117
- stdin.pause();
118
- stdin.removeListener('data', onData);
119
- process.stderr.write('\n');
120
- process.exit(130);
121
- } else if (ch === '\u007f' || ch === '\b') {
122
- buf = buf.slice(0, -1);
123
- } else if (ch >= ' ') {
124
- buf += ch;
125
- }
126
- }
127
- };
128
- stdin.on('data', onData);
129
- });
130
- }
131
-
132
- export async function authLogin(args, flags, ctx) {
133
- let token = flags.token;
134
- let viaRefresh = false;
135
-
136
- if (flags.clipboard) {
137
- // read the token from the clipboard (e.g. extracted from the wetaca.com DevTools console)
138
- const { execSync } = child_process;
139
- try {
140
- const out = process.platform === 'win32'
141
- ? execSync('powershell -NoProfile -Command Get-Clipboard', { encoding: 'utf8' })
142
- : process.platform === 'darwin' ? execSync('pbpaste', { encoding: 'utf8' })
143
- : execSync('xclip -selection clipboard -o', { encoding: 'utf8' });
144
- const m = String(out).match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
145
- token = m ? m[0] : String(out).trim();
146
- } catch (e) {
147
- throw usageError('Could not read the clipboard: ' + e.message);
148
- }
149
- if (!token) throw usageError('The clipboard is empty.');
150
- }
151
-
152
- let customer = null;
153
- // --cookies FILE / --cookies-stdin: importar desde un export del navegador.
154
- // Netscape cookies.txt, JSON Cookie-Editor/EditThisCookie, header
155
- // Cookie: o valor pelado. Solo se leen cookies de wetaca.com.
156
- let cookieFileInput = null;
157
- if (flags.cookies || flags['cookies-stdin']) {
158
- try {
159
- if (flags['cookies-stdin']) {
160
- cookieFileInput = fs.readFileSync(0, 'utf8');
161
- } else {
162
- cookieFileInput = fs.readFileSync(String(flags.cookies).trim(), 'utf8');
163
- }
164
- } catch (e) {
165
- throw usageError('Could not read the cookies file: ' + e.message);
166
- }
167
- }
168
- if (cookieFileInput != null || flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN) {
169
- // Import the refresh-token from the web (120-day cookie)
170
- // and let /session/refresh mint the session tokens. No password is ever requested.
171
- let rt;
172
- if (cookieFileInput != null) {
173
- rt = extractRefreshToken(cookieFileInput);
174
- } else {
175
- rt = String(flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN).trim();
176
- }
177
- if (!rt) {
178
- throw new CliError(EXIT.AUTH,
179
- 'The cookie export contains no "refresh-token" cookie from wetaca.com. ' +
180
- 'Make sure to export the cookies while logged in to wetaca.com (the cookie is created on login).',
181
- { reason: 'refresh_token_missing', suggested_commands: ['wetaca auth login --refresh-token VALOR'] });
182
- }
183
- saveProfile(ctx.profile, { refreshToken: rt });
184
- try {
185
- token = await sessionRefresh(rt, ctx.profile, ctx.debug);
186
- viaRefresh = true;
187
- } catch (e) {
188
- throw new CliError(e.exitCode || EXIT.AUTH,
189
- 'Could not refresh the session with that refresh-token. ' + e.message,
190
- { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
191
- }
192
- const c = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
193
- customer = c.customer;
194
- } else if (token) {
195
- // token supplied directly (advanced). Limpiar y validar llamando a la API de verdad
196
- // (the test that matters is that `customer` responds; tokenIsValid is diagnostics only).
197
- token = token.trim().replace(/^["']|["']$/g, '').replace(/^Bearer\s+/i, '');
198
- if (!token) throw usageError('The token was empty.');
199
- try {
200
- const d = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
201
- customer = d.customer;
202
- } catch (e) {
203
- let isValid = null;
204
- try {
205
- const v = await gql(Q.TOKEN_IS_VALID, { token }, { token, debug: ctx.debug });
206
- isValid = v.tokenIsValid;
207
- } catch { /* seguimos con el error original */ }
208
- throw new CliError(EXIT.AUTH,
209
- `The API rejected the token${isValid === false ? ' (tokenIsValid=false)' : ''}. ` +
210
- 'Check that you copied ONLY what comes after "Bearer " in the authorization header ' +
211
- '(without the word Bearer, without quotes). Original error: ' + e.message,
212
- { reason: 'invalid_token' });
213
- }
214
- } else {
215
- // Without --refresh-token or --token: prompt for it on the terminal (hidden). Accepts the
216
- // refresh-token cookie (preferred, lasts 120 days) or a direct session JWT.
217
- if (ctx.noInput || !process.stdin.isTTY) {
218
- throw usageError('Without a terminal you need --refresh-token VALUE (a wetaca.com cookie, F12 → Application → Cookies), or --token VALUE / --token --clipboard.');
219
- }
220
- const pasted = await ask('Paste the refresh-token (or the session token) and press Enter: ', { hidden: true });
221
- const v = (pasted || '').trim().replace(/^["']|["']$/g, '');
222
- if (!v) throw usageError('No token was pasted.');
223
- if (v.startsWith('eyJ')) {
224
- token = v; // direct session JWT
225
- } else {
226
- saveProfile(ctx.profile, { refreshToken: v });
227
- try {
228
- token = await sessionRefresh(v, ctx.profile, ctx.debug);
229
- viaRefresh = true;
230
- } catch (e) {
231
- throw new CliError(e.exitCode || EXIT.AUTH,
232
- 'Could not refresh the session with that refresh-token. ' + e.message,
233
- { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
234
- }
235
- }
236
- try {
237
- const c = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
238
- customer = c.customer;
239
- } catch (e) {
240
- throw new CliError(EXIT.AUTH, 'The API rejected the token. Original error: ' + e.message,
241
- { reason: 'invalid_token' });
242
- }
243
- }
244
-
245
- // The session token and (if imported) the refresh-token are saved. NEVER the password.
246
- saveProfile(ctx.profile, {
247
- token,
248
- email: customer?.email || null,
249
- });
250
- return {
251
- ok: true, profile: ctx.profile, email: customer?.email || null,
252
- via: viaRefresh ? 'refresh-token (auto-renewable ~120 days)' : 'session token (expires; renew it with --refresh-token)',
253
- token: token.slice(0, 8) + '…',
254
- };
255
- }
256
-
257
- export async function authStatus(args, flags, ctx) {
258
- const token = getToken(ctx.profile);
259
- if (!token) return { authenticated: false, profile: ctx.profile };
260
- let authenticated = false, customer = null, err = null, tokenValid = null;
261
- try {
262
- const c = await gql(Q.CUSTOMER, {}, { profile: ctx.profile, debug: ctx.debug });
263
- customer = c.customer;
264
- authenticated = true;
265
- } catch (e) {
266
- err = e.message;
267
- try {
268
- const v = await gql(Q.TOKEN_IS_VALID, { token }, { profile: ctx.profile, debug: ctx.debug });
269
- tokenValid = v.tokenIsValid;
270
- } catch { /* el error de customer manda */ }
271
- }
272
- return { authenticated, profile: ctx.profile, customer, tokenValid, error: err };
273
- }
274
-
275
- export async function authLogout(args, flags, ctx) {
276
- const token = getToken(ctx.profile);
277
- if (token) { try { await gql(Q.LOGOUT, {}, { profile: ctx.profile, debug: ctx.debug }); } catch { /* best effort */ } }
278
- const cfg = loadConfig();
279
- if (cfg.profiles?.[ctx.profile]) { cfg.profiles[ctx.profile].token = null; saveConfig(cfg); }
280
- const creds = loadCreds();
281
- if (creds.profiles?.[ctx.profile]) { creds.profiles[ctx.profile].token = null; saveCreds(creds); }
282
- return { ok: true, profile: ctx.profile };
283
- }
284
-
285
- // ---------- me ----------
286
-
287
- export async function meShow(args, flags, ctx) {
288
- const c = await gql(Q.CUSTOMER, {}, { profile: ctx.profile, debug: ctx.debug });
289
- const s = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
290
- const w = await gql(Q.WALLET, {}, { profile: ctx.profile, debug: ctx.debug });
291
- const acc = s.subscriptionAccountByCustomer;
292
- return {
293
- customer: c.customer,
294
- subscription: acc ? { id: acc.id, isActive: acc.isActive, cancelled: acc.cancelled, pausedUntil: acc.pausedUntil } : null,
295
- walletBalance: w.walletBalance,
296
- walletBalanceEur: w.walletBalance != null ? cents(w.walletBalance) : null,
297
- };
298
- }
299
-
300
- // ---------- subscription ----------
301
-
302
- export async function subShow(args, flags, ctx) {
303
- const d = await gql(Q.SUBSCRIPTION_FULL, {}, { profile: ctx.profile, debug: ctx.debug });
304
- const acc = d.subscriptionAccountByCustomer;
305
- return {
306
- id: acc.id,
307
- isActive: acc.isActive,
308
- cancelled: acc.cancelled,
309
- pausedUntil: acc.pausedUntil,
310
- dateCreated: acc.dateCreated,
311
- delivery: acc.delivery,
312
- pricing: acc.subscriptionAccountPricing,
313
- pricingEur: {
314
- toPay: cents(acc.subscriptionAccountPricing?.toPay),
315
- shipping: cents(acc.subscriptionAccountPricing?.shipping),
316
- },
317
- recurring: acc.recurringSubscriptionType,
318
- profiles: acc.profiles?.map((p) => ({ id: p.id, name: p.name, email: p.email, price: p.price, priceEur: cents(p.price), isActive: p.isActive })),
319
- nextSuggestion: d.nextSuggestion,
320
- };
321
- }
322
-
323
- export async function subPause(args, flags, ctx) {
324
- const weeks = flags.weeks ? parseInt(flags.weeks, 10) : null;
325
- if (flags.weeks && (!Number.isInteger(weeks) || weeks < 1)) {
326
- throw usageError('--weeks must be an integer ≥ 1.');
327
- }
328
- const d0 = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
329
- const acc = d0.subscriptionAccountByCustomer;
330
- if (!acc?.isActive) throw new CliError(EXIT.API, 'The subscription is not active; nothing to pause.', { reason: 'not_active' });
331
- const summary = `Pause subscription ${acc.id}${weeks ? ` for ${weeks} week(s)` : ' (indefinite pause)'}.`;
332
- await confirm(flags, summary);
333
- const d = await gql(Q.CANCEL_SUBSCRIPTION, {
334
- subscriptionAccountId: acc.id, path: '/pausar', pausedWeeks: weeks, feedback: flags.feedback || null,
335
- }, { profile: ctx.profile, debug: ctx.debug });
336
- return { ok: true, paused: d.subscriptionAccount };
337
- }
338
-
339
- export async function subResume(args, flags, ctx) {
340
- const d0 = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
341
- const acc = d0.subscriptionAccountByCustomer;
342
- if (!acc) throw new CliError(EXIT.NOT_FOUND, 'No subscription account in this profile.', { reason: 'no_account' });
343
- if (acc.isActive) return { ok: true, alreadyActive: true, subscriptionAccount: acc };
344
- await confirm(flags, `Resume subscription ${acc.id}.`);
345
- const d = await gql(Q.ACTIVATE_SUBSCRIPTION, { subscriptionAccountId: acc.id }, { profile: ctx.profile, debug: ctx.debug });
346
- return { ok: true, subscriptionAccount: d.subscriptionAccount };
347
- }
348
-
349
- // ---------- suggestion (menu semanal) ----------
350
-
351
- export async function sugShow(args, flags, ctx) {
352
- const d = await gql(Q.NEXT_SUGGESTION, {}, { profile: ctx.profile, debug: ctx.debug });
353
- const s = d.nextSuggestion;
354
- if (!s) throw new CliError(EXIT.NOT_FOUND, 'No active suggestion for next week.', { reason: 'no_suggestion' });
355
- return {
356
- id: s.id,
357
- skip: s.skip,
358
- pausedAt: s.pausedAt,
359
- validUntil: s.validUntil,
360
- isBeingCharged: s.isBeingCharged,
361
- deliveryWindow: s.delivery?.option ? { start: s.delivery.option.start, end: s.delivery.option.end } : null,
362
- address: s.delivery?.address,
363
- week: s.menuMetadata,
364
- pricing: s.suggestionPricing,
365
- pricingEur: {
366
- toPay: cents(s.suggestionPricing?.toPay),
367
- shipping: cents(s.suggestionPricing?.shipping),
368
- profiles: cents(s.suggestionPricing?.profilesTotal?.toPay),
369
- },
370
- profiles: s.profileSuggestions?.map((ps) => ({
371
- profileSuggestionId: ps.id,
372
- profileId: ps.profileId,
373
- skip: ps.skip,
374
- hasChanges: ps.hasChanges,
375
- products: ps.products,
376
- productMap: ps.productMap,
377
- })),
378
- };
379
- }
380
-
381
- export async function sugPause(args, flags, ctx) {
382
- const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
383
- await confirm(flags, `Skip (pause) next week's delivery (suggestion ${sid}).`);
384
- const d = await gql(Q.PAUSE_SUGGESTION, { suggestionId: sid, path: '/menu', feedback: flags.feedback || null }, { profile: ctx.profile, debug: ctx.debug });
385
- return { ok: true, paused: d.paused };
386
- }
387
-
388
- export async function sugResume(args, flags, ctx) {
389
- const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
390
- await confirm(flags, `Resume next week's delivery (suggestion ${sid}).`);
391
- const d = await gql(Q.RESUME_SUGGESTION, { suggestionId: sid }, { profile: ctx.profile, debug: ctx.debug });
392
- return { ok: true, resumed: d.resumed };
393
- }
394
-
395
- // `suggestion edit --profile-suggestion ID --set "productId:qty,productId:qty"`
396
- export async function sugEdit(args, flags, ctx) {
397
- const psid = requireId(flags['profile-suggestion'] || flags.profileSuggestion, '--profile-suggestion');
398
- if (!flags.set) throw usageError('Missing --set "productId:qty,...". Example: --set "abc123:2,def456:1".');
399
- const productsInput = flags.set.split(',').map((pair) => {
400
- const [id, qty] = pair.split(':').map((x) => x.trim());
401
- if (!id || !qty) throw usageError(`Invalid pair in --set: '${pair}' (id:qty format).`);
402
- const n = parseInt(qty, 10);
403
- if (!Number.isInteger(n) || n < 0) throw usageError(`Invalid quantity in '${pair}'.`);
404
- return { id, quantity: n };
405
- });
406
- const payload = { profileSuggestionId: psid, productsInput, resumeAccountSuggestion: flags.resume === undefined ? undefined : flags.resume === 'true' || flags.resume === true };
407
- if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'editProfileSuggestionMenu', variables: payload } };
408
- await confirm(flags, `Change the menu of profile-suggestion ${psid} to: ${flags.set}.`);
409
- const d = await gql(Q.EDIT_PROFILE_SUGGESTION_MENU, payload, { profile: ctx.profile, debug: ctx.debug });
410
- return { ok: true, result: d.editProfileSuggestionProducts };
411
- }
412
-
413
- // ---------- deliveries / orders ----------
414
-
415
- export async function deliveriesNext(args, flags, ctx) {
416
- const d = await gql(Q.PENDING_DELIVERY, {}, { profile: ctx.profile, debug: ctx.debug });
417
- return d;
418
- }
419
-
420
- export async function ordersList(args, flags, ctx) {
421
- const limit = parseInt(flags.limit || '10', 10);
422
- const offset = parseInt(flags.offset || '0', 10);
423
- const d = await gql(Q.PREVIOUS_DELIVERIES, { limit, offset }, { profile: ctx.profile, debug: ctx.debug });
424
- const rows = d.previousDeliveries.map((o) => ({ ...o, priceEur: cents(o.price) }));
425
- return ctx.format === 'json' || ctx.format === 'jsonl' ? rows : { items: rows, limit, offset, count: rows.length };
426
- }
427
-
428
- export async function ordersShow(args, flags, ctx) {
429
- const id = parseInt(requireId(args[0], '<order-id>'), 10);
430
- if (!Number.isInteger(id)) throw usageError('The order id must be numeric.');
431
- const d = await gql(Q.ORDER_DETAILS, { id }, { profile: ctx.profile, debug: ctx.debug });
432
- return { ...d.order, priceEur: cents(d.order.price) };
433
- }
434
-
435
- export async function ordersCancel(args, flags, ctx) {
436
- const id = parseInt(requireId(args[0], '<order-id>'), 10);
437
- if (!Number.isInteger(id)) throw usageError('The order id must be numeric.');
438
- if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'cancelConfirmedOrder', variables: { orderId: id } } };
439
- await confirm(flags, `Cancel order ${id} (takes effect on Wetaca).`);
440
- const d = await gql(Q.CANCEL_ORDER, { orderId: id }, { profile: ctx.profile, debug: ctx.debug });
441
- return { ok: true, cancelled: d.cancelConfirmedOrder, refundEur: cents(d.cancelConfirmedOrder?.amount) };
442
- }
443
-
444
- // ---------- addresses / vouchers ----------
445
-
446
- export async function addrList(args, flags, ctx) {
447
- const d = await gql(Q.ADDRESSES, {}, { profile: ctx.profile, debug: ctx.debug });
448
- return d.addresses;
449
- }
450
-
451
- // Changes the delivery address: creates the new address (saveAddress) and assigns it
452
- // to the subscription (editDeliveryAccountInfo) and to next week's suggestion
453
- // (editSuggestionDelivery), keeping the current delivery option. Flow identical to the web's.
454
- export async function addrSave(args, flags, ctx) {
455
- const f = (k) => (flags[k] != null ? String(flags[k]).trim() : undefined);
456
- const street = f('street'), number = f('number'), zipcode = f('zipcode'), city = f('city');
457
- if (!street || !number || !zipcode || !city) {
458
- throw usageError('Missing fields: --street, --number, --zipcode and --city are required ' +
459
- '(optional: --floor, --notes, --firstname, --lastname, --phone; by default they are inherited from your current address).');
460
- }
461
- const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
462
- const sub = cur.subscriptionAccountByCustomer;
463
- const curAddr = sub?.delivery?.address || {};
464
- const deliveryOptionId = sub?.delivery?.option?.id;
465
- const suggestion = cur.nextSuggestion;
466
- if (!deliveryOptionId) throw new CliError(EXIT.DRIFT, 'Could not read the current delivery option of your subscription.', { reason: 'no_delivery_option' });
467
-
468
- const address = {
469
- firstname: f('firstname') ?? curAddr.firstname,
470
- lastname: f('lastname') ?? curAddr.lastname,
471
- street,
472
- number,
473
- floor: f('floor') ?? curAddr.floor ?? null,
474
- zipcode: parseInt(zipcode, 10),
475
- city,
476
- phone: f('phone') ?? curAddr.phone,
477
- notes: f('notes') ?? curAddr.notes ?? null,
478
- };
479
- if (address.zipcode == null || Number.isNaN(address.zipcode)) throw usageError('--zipcode must be numeric.');
480
- // NOTE: deliveryConfiguration does NOT carry "type" — the API returns 500 if you send it
481
- // (tested live; the valid shape is {optionConfiguration: {addressId, deliveryOptionId}}).
482
- const deliveryConfiguration = { optionConfiguration: { addressId: null, deliveryOptionId } };
483
- const plan = {
484
- saveAddress: address,
485
- subscription: sub ? { mutation: 'editDeliveryAccountInfo', deliveryConfiguration } : null,
486
- suggestion: suggestion ? { mutation: 'editSuggestionDelivery', suggestionId: suggestion.id, deliveryConfiguration } : null,
487
- };
488
- if (ctx.dryRun) return { dryRun: true, wouldSend: plan };
489
- await confirm(flags, `Change your delivery address to ${street} ${number}${address.floor ? ', ' + address.floor : ''} (${address.zipcode} ${city}).`);
490
- const saved = await gql(Q.SAVE_ADDRESS, { address }, { profile: ctx.profile, debug: ctx.debug });
491
- const addressId = saved.saveAddress.id;
492
- const deliveryConfiguration2 = { optionConfiguration: { addressId, deliveryOptionId } };
493
- const subRes = sub ? await gql(Q.EDIT_SUBSCRIPTION_DELIVERY,
494
- { subscriptionDeliveryInput: { deliveryConfiguration: deliveryConfiguration2 } },
495
- { profile: ctx.profile, debug: ctx.debug }) : null;
496
- const sugRes = suggestion ? await gql(Q.EDIT_SUGGESTION_DELIVERY,
497
- { suggestionId: suggestion.id, suggestionDeliveryInput: { deliveryConfiguration: deliveryConfiguration2 } },
498
- { profile: ctx.profile, debug: ctx.debug }) : null;
499
- return {
500
- ok: true,
501
- address: saved.saveAddress,
502
- phoneCarriedFromPrevious: !flags.phone && !!curAddr.phone,
503
- subscriptionUpdated: subRes?.editDeliveryAccountInfo?.id === sub.id,
504
- suggestionUpdated: sugRes?.editSuggestionDelivery?.id === suggestion.id,
505
- };
506
- }
507
-
508
- // ---------- catalog ----------
509
-
510
- // Weekly menu available for your zipcode (ids are the ones used by suggestion edit --set)
511
- export async function menuList(args, flags, ctx) {
512
- const zipcode = flags.zipcode != null ? parseInt(flags.zipcode, 10) : undefined;
513
- const d = await gql(Q.SEGMENT_MENU, { zipcode, isSubscriptionIntent: true }, { profile: ctx.profile, debug: ctx.debug });
514
- const m = d.segmentMenu;
515
- if (!m) throw new CliError(EXIT.NOT_FOUND, 'No menu available for that postal code.', { reason: 'no_menu' });
516
- return { week: m.week, year: m.year, dateFrom: m.dateFrom, dateTo: m.dateTo, dishes: m.dishes };
517
- }
518
-
519
- export async function dishShow(args, flags, ctx) {
520
- const slug = args[0];
521
- if (!slug) throw usageError('Usage: wetaca dish show <slug> (slugs come from `wetaca menu list`)');
522
- const d = await gql(Q.DISH, { slug }, { profile: ctx.profile, debug: ctx.debug });
523
- if (!d.dish) throw new CliError(EXIT.NOT_FOUND, `Dish '${slug}' does not exist.`, { reason: 'not_found' });
524
- return d.dish;
525
- }
526
-
527
- // ---------- franja de entrega ----------
528
-
529
- export async function delivOptions(args, flags, ctx) {
530
- const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
531
- const zipcode = flags.zipcode != null ? parseInt(flags.zipcode, 10) : cur.subscriptionAccountByCustomer?.delivery?.address?.zipcode;
532
- if (!zipcode) throw usageError('Could not read your postal code; pass it with --zipcode.');
533
- const d = await gql(Q.DELIVERY_OPTIONS, { zipcode }, { profile: ctx.profile, debug: ctx.debug });
534
- const currentId = cur.subscriptionAccountByCustomer?.delivery?.option?.id;
535
- return d.deliveryOptions.map((o) => ({ ...o, isCurrent: o.id === currentId, priceEur: cents(o.price) }));
536
- }
537
-
538
- // Changes the delivery slot (option) for the subscription and next week.
539
- export async function delivSetOption(args, flags, ctx) {
540
- const optionId = parseInt(requireId(args[0], '<option-id>'), 10);
541
- if (!Number.isInteger(optionId)) throw usageError('The delivery window id must be numeric (they come from `wetaca deliveries options`).');
542
- const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
543
- const sub = cur.subscriptionAccountByCustomer;
544
- const suggestion = cur.nextSuggestion;
545
- const curOption = sub?.delivery?.option;
546
- if (!curOption) throw new CliError(EXIT.DRIFT, 'Could not read the current delivery window.', { reason: 'no_delivery_option' });
547
- const opts = await gql(Q.DELIVERY_OPTIONS, { zipcode: sub?.delivery?.address?.zipcode }, { profile: ctx.profile, debug: ctx.debug });
548
- const opt = (opts.deliveryOptions || []).find((o) => o.id === optionId);
549
- if (!opt) throw new CliError(EXIT.NOT_FOUND,
550
- `Delivery window ${optionId} is not available for your postal code. Available: ${(opts.deliveryOptions || []).map((o) => o.id).join(', ')}`,
551
- { reason: 'option_not_available' });
552
- const deliveryConfiguration = { optionConfiguration: { deliveryOptionId: optionId, addressId: sub?.delivery?.address?.id } };
553
- const plan = {
554
- option: opt,
555
- subscription: { mutation: 'editDeliveryAccountInfo', deliveryConfiguration },
556
- suggestion: suggestion ? { mutation: 'editSuggestionDelivery', suggestionId: suggestion.id, deliveryConfiguration } : null,
557
- };
558
- if (ctx.dryRun) return { dryRun: true, wouldSend: plan };
559
- await confirm(flags, `Change your delivery window to ${fmtWindow(opt)} (was ${fmtWindow(curOption)}).`);
560
- const subRes = await gql(Q.EDIT_SUBSCRIPTION_DELIVERY,
561
- { subscriptionDeliveryInput: { deliveryConfiguration } }, { profile: ctx.profile, debug: ctx.debug });
562
- const sugRes = suggestion ? await gql(Q.EDIT_SUGGESTION_DELIVERY,
563
- { suggestionId: suggestion.id, suggestionDeliveryInput: { deliveryConfiguration } },
564
- { profile: ctx.profile, debug: ctx.debug }) : null;
565
- return {
566
- ok: true,
567
- option: opt,
568
- subscriptionUpdated: subRes?.editDeliveryAccountInfo?.id === sub.id,
569
- suggestionUpdated: sugRes?.editSuggestionDelivery?.id === suggestion.id,
570
- };
571
- }
572
-
573
- // ---------- perfiles ----------
574
-
575
- export async function profilesList(args, flags, ctx) {
576
- const d = await gql(Q.PROFILES, {}, { profile: ctx.profile, debug: ctx.debug });
577
- const s = d.subscriptionAccountByCustomer;
578
- return { subscriptionId: s.id, isActive: s.isActive, pausedUntil: s.pausedUntil, profiles: s.profiles };
579
- }
580
-
581
- async function resolveProfileId(args) {
582
- const key = requireId(args[0], '<profile-id|name>');
583
- const d = await gql(Q.PROFILES, {}, {});
584
- const profiles = d.subscriptionAccountByCustomer?.profiles || [];
585
- const p = profiles.find((x) => x.id === key || x._id === key
586
- || x.name?.toLowerCase() === key.toLowerCase());
587
- if (!p) throw new CliError(EXIT.NOT_FOUND,
588
- `Profile '${key}' does not exist. Profiles: ${profiles.map((x) => `${x.name} (${x.id})`).join(', ')}`,
589
- { reason: 'not_found' });
590
- return p;
591
- }
592
-
593
- export async function profilesPause(args, flags, ctx) {
594
- const p = await resolveProfileId(args);
595
- if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'pauseProfile', profileId: p.id } };
596
- await confirm(flags, `Pause profile '${p.name}' (stops receiving tuppers for that profile).`);
597
- const d = await gql(Q.PAUSE_PROFILE, { profileId: p.id }, { profile: ctx.profile, debug: ctx.debug });
598
- return { ok: true, profile: d.pauseProfile };
599
- }
600
-
601
- export async function profilesResume(args, flags, ctx) {
602
- const p = await resolveProfileId(args);
603
- if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'resumeProfile', profileId: p.id } };
604
- await confirm(flags, `Resume profile '${p.name}'.`);
605
- const d = await gql(Q.RESUME_PROFILE, { profileId: p.id }, { profile: ctx.profile, debug: ctx.debug });
606
- return { ok: true, profile: d.resumeProfile };
607
- }
608
-
609
- // Deletes a saved address. Protection: if it is in use by the subscription or
610
- // next week, it requires assigning another one first (addresses save).
611
- export async function addrRemove(args, flags, ctx) {
612
- const id = parseInt(requireId(args[0], '<address-id>'), 10);
613
- if (!Number.isInteger(id)) throw usageError('The address id must be numeric (they come from `wetaca addresses list`).');
614
- const d0 = await gql(Q.ADDRESSES, {}, { profile: ctx.profile, debug: ctx.debug });
615
- const a = (d0.addresses || []).find((x) => x.id === id);
616
- if (!a) throw new CliError(EXIT.NOT_FOUND, `Address ${id} does not exist.`, { reason: 'not_found' });
617
- if (a.isSubscriptionAddress || a.isSuggestionAddress) {
618
- throw usageError(`Address ${id} (${a.street} ${a.number}) is in use; first assign another with \`wetaca addresses save\`.`);
619
- }
620
- if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'removeAddress', addressId: id } };
621
- await confirm(flags, `Delete address ${id} (${a.street} ${a.number}, ${a.zipcode} ${a.city}).`);
622
- const d = await gql(Q.REMOVE_ADDRESS, { addressId: id }, { profile: ctx.profile, debug: ctx.debug });
623
- return { ok: true, removed: d.removeAddress?.id === id, addressId: id };
624
- }
625
-
626
- export async function vouchersList(args, flags, ctx) {
627
- const d = await gql(Q.VOUCHERS, {}, { profile: ctx.profile, debug: ctx.debug });
628
- return d.vouchers.map((v) => ({
629
- ...v,
630
- discountEur: v.discount?.price != null ? cents(v.discount.price) : null,
631
- subscriptionDiscountEur: v.subscriptionDiscount?.price != null ? cents(v.subscriptionDiscount.price) : null,
632
- }));
633
- }
634
-
635
- export async function walletShow(args, flags, ctx) {
636
- const d = await gql(Q.WALLET, {}, { profile: ctx.profile, debug: ctx.debug });
637
- return { balance: d.walletBalance, balanceEur: cents(d.walletBalance) };
638
- }
639
-
640
- // ---------- config ----------
641
-
642
- export async function configCmd(verb, args, flags, ctx) {
643
- if (verb === 'path') return { config: configPath(), credentials: credentialsPath() };
644
- const cfg = loadConfig();
645
- if (verb === 'list') return { defaultProfile: cfg.defaultProfile, config: { ...cfg.profiles, _meta: { redacted: true } }, note: 'tokens are not shown' };
646
- if (verb === 'get') {
647
- const key = args[0];
648
- if (!key) throw usageError('Missing key: config get <dotted.path>');
649
- const val = key.split('.').reduce((acc, k) => acc?.[k], cfg);
650
- return { key, value: val === undefined ? null : (String(key).endsWith('token') ? '***' : val) };
651
- }
652
- if (verb === 'set') {
653
- const [key, ...rest] = args;
654
- if (!key || rest.length === 0) throw usageError('Usage: config set <key> <value>');
655
- if (key.endsWith('token')) throw usageError('The token is managed with `wetaca auth login --token`.');
656
- const value = rest.join(' ') === 'true' ? true : rest.join(' ') === 'false' ? false : rest.join(' ');
657
- const parts = key.split('.');
658
- let obj = cfg;
659
- for (let i = 0; i < parts.length - 1; i++) obj = (obj[parts[i]] ??= {});
660
- obj[parts[parts.length - 1]] = value;
661
- saveConfig(cfg);
662
- return { ok: true, key, value };
663
- }
664
- throw usageError(`Config verbs: path | list | get | set`);
665
- }
666
-
667
- // ---------- doctor ----------
668
-
669
- export async function doctor(args, flags, ctx) {
670
- const checks = [];
671
- const push = (name, ok, detail) => checks.push({ check: name, ok, detail });
672
-
673
- const nodeOk = parseInt(process.versions.node.split('.')[0], 10) >= 18;
674
- push('node >= 18', nodeOk, process.versions.node);
675
-
676
- let apiOk = false, apiDetail;
677
- try {
678
- const res = await fetch(process.env.WETACA_API_URL || 'https://api.wetaca.com/graphql', {
679
- method: 'POST', headers: { 'Content-Type': 'application/json' },
680
- body: JSON.stringify({ query: 'query { __typename }' }),
681
- });
682
- const j = await res.json();
683
- apiOk = res.ok && !!j.data?.__typename;
684
- apiDetail = `HTTP ${res.status}`;
685
- } catch (e) { apiDetail = `no connection: ${e.cause?.code || e.message}`; }
686
- push('api.wetaca.com reachable', apiOk, apiDetail);
687
-
688
- const token = getToken(ctx.profile);
689
- push('session present', !!token, token ? 'token configured' : 'no token — wetaca auth login');
690
- if (token) {
691
- try {
692
- const d = await gql(Q.TOKEN_IS_VALID, { token }, { profile: ctx.profile, debug: ctx.debug });
693
- push('token valid', d.tokenIsValid === true, `tokenIsValid=${d.tokenIsValid}`);
694
- } catch (e) {
695
- push('token valid', false, e.message);
696
- }
697
- }
698
- push('config directory', true, configDir());
699
- return { ok: checks.every((c) => c.ok), checks };
700
- }
1
+ // wetaca-cli command implementations.
2
+ import readline from 'node:readline/promises';
3
+ import child_process from 'node:child_process';
4
+ import fs from 'node:fs';
5
+ import {
6
+ CliError, usageError, EXIT, gql, cents, fmtDate, emit,
7
+ getToken, loadConfig, saveConfig, saveProfile, configPath, configDir,
8
+ loadCreds, saveCreds, credentialsPath, sessionRefresh,
9
+ } from './lib.js';
10
+ import * as Q from './queries.js';
11
+
12
+ // ---------- helpers ----------
13
+
14
+ // Extrae la cookie refresh-token de wetaca.com de un export del navegador.
15
+ // Formatos aceptados: Netscape cookies.txt, JSON de
16
+ // Cookie-Editor/EditThisCookie (array o {url, cookies}), lista de cookies DevTools,
17
+ // cabecera "Cookie: ..." o el valor pelado.
18
+ export function extractRefreshToken(text) {
19
+ const t = String(text || '').trim();
20
+ if (!t) return null;
21
+ // JSON: array de cookies o {url, cookies}
22
+ if (t.startsWith('[') || t.startsWith('{')) {
23
+ try {
24
+ const j = JSON.parse(t);
25
+ const list = Array.isArray(j) ? j : (Array.isArray(j.cookies) ? j.cookies : null);
26
+ if (list) {
27
+ const c = list.find((x) => x && /(^|\.)wetaca\.com$/i.test(String(x.domain || ''))
28
+ && x.name === 'refresh-token');
29
+ return c?.value ? String(c.value) : null;
30
+ }
31
+ } catch { /* no era JSON, seguimos */ }
32
+ }
33
+ // Netscape cookies.txt: domain \t flag \t path \t secure \t expiry \t name \t value
34
+ // (httpOnly cookies carry the "#HttpOnly_" prefix on the line)
35
+ const lines = t.split(/\r?\n/);
36
+ for (const raw of lines) {
37
+ if (!raw) continue;
38
+ const line = raw.startsWith('#HttpOnly_') ? raw.slice('#HttpOnly_'.length) : raw;
39
+ if (line.startsWith('#')) continue;
40
+ const parts = line.split('\t');
41
+ if (parts.length >= 7 && /(^|\.)wetaca\.com$/i.test(parts[0]) && parts[5] === 'refresh-token') {
42
+ return parts[6] || null;
43
+ }
44
+ }
45
+ // Cabecera "Cookie: name=value; name=value" o pares sueltos
46
+ const m = t.match(/(?:^|[\s;])refresh-token=([^;\s"']+)/);
47
+ if (m) return m[1];
48
+ // Bare value (a single line with no tabs and no ';'); an "=" can be base64 padding
49
+ if (lines.length === 1 && !t.includes('\t') && !t.includes(';')) {
50
+ const eq = t.indexOf('=');
51
+ if (eq === -1) return t;
52
+ const name = t.slice(0, eq);
53
+ // si lo que hay antes del "=" es el nombre de una cookie conocida, no es un valor pelado
54
+ const KNOWN = ['refresh-token', 'auth-token', 'customer-token', 'token-voucher-pending'];
55
+ return KNOWN.includes(name) ? null : t;
56
+ }
57
+ return null;
58
+ }
59
+
60
+ async function confirm(flags, summary) {
61
+ if (flags.yes) return;
62
+ if (flags.noInput || !process.stdin.isTTY) {
63
+ throw usageError(
64
+ `Real-effect operation; confirmation required. Summary: ${summary}\n` +
65
+ 'No terminal: repeat with --yes to confirm.',
66
+ { reason: 'confirmation_required', suggested_commands: ['repeat the command with --yes'] });
67
+ }
68
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr });
69
+ const ans = (await rl.question(`\n${summary}\nConfirm? [y/N] `)).trim().toLowerCase();
70
+ rl.close();
71
+ if (ans !== 'y' && ans !== 'yes' && ans !== 's' && ans !== 'si') {
72
+ throw usageError('Cancelled by the user.', { reason: 'declined' });
73
+ }
74
+ }
75
+
76
+ function requireId(v, what) {
77
+ if (!v) throw usageError(`Missing <${what}>.`);
78
+ return v;
79
+ }
80
+
81
+ async function nextSuggestionId(profile, debug) {
82
+ const d = await gql(`query nextSuggestionId { nextSuggestion { id } }`, {}, { profile, debug });
83
+ if (!d.nextSuggestion?.id) {
84
+ throw new CliError(EXIT.NOT_FOUND, 'No active suggestion for next week.', { reason: 'no_suggestion' });
85
+ }
86
+ return d.nextSuggestion.id;
87
+ }
88
+
89
+ // ---------- auth ----------
90
+
91
+ // Pregunta por terminal; hidden=true lee en modo raw (sin eco, como sudo)
92
+ function ask(question, { hidden = false } = {}) {
93
+ return new Promise((resolve) => {
94
+ if (!hidden) {
95
+ // API de promesas (readline/promises): question() devuelve Promise, no acepta callback
96
+ const rl = readline.createInterface({ input: process.stdin, output: process.stderr, terminal: true });
97
+ rl.question(question).then((a) => { rl.close(); resolve(a.trim()); });
98
+ return;
99
+ }
100
+ const stdin = process.stdin;
101
+ process.stderr.write(question);
102
+ const wasRaw = stdin.isRaw;
103
+ stdin.setRawMode(true);
104
+ stdin.resume(); // mantiene vivo el loop tras cerrar el readline del email
105
+ let buf = '';
106
+ const onData = (chunk) => {
107
+ for (const ch of String(chunk)) {
108
+ if (ch === '\r' || ch === '\n') {
109
+ stdin.setRawMode(wasRaw);
110
+ stdin.pause();
111
+ stdin.removeListener('data', onData);
112
+ process.stderr.write('\n');
113
+ resolve(buf.trim());
114
+ return;
115
+ } else if (ch === '\u0003') { // Ctrl+C
116
+ stdin.setRawMode(wasRaw);
117
+ stdin.pause();
118
+ stdin.removeListener('data', onData);
119
+ process.stderr.write('\n');
120
+ process.exit(130);
121
+ } else if (ch === '\u007f' || ch === '\b') {
122
+ buf = buf.slice(0, -1);
123
+ } else if (ch >= ' ') {
124
+ buf += ch;
125
+ }
126
+ }
127
+ };
128
+ stdin.on('data', onData);
129
+ });
130
+ }
131
+
132
+ export async function authLogin(args, flags, ctx) {
133
+ let token = flags.token;
134
+ let viaRefresh = false;
135
+
136
+ if (flags.clipboard) {
137
+ // read the token from the clipboard (e.g. extracted from the wetaca.com DevTools console)
138
+ const { execSync } = child_process;
139
+ try {
140
+ const out = process.platform === 'win32'
141
+ ? execSync('powershell -NoProfile -Command Get-Clipboard', { encoding: 'utf8' })
142
+ : process.platform === 'darwin' ? execSync('pbpaste', { encoding: 'utf8' })
143
+ : execSync('xclip -selection clipboard -o', { encoding: 'utf8' });
144
+ const m = String(out).match(/eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/);
145
+ token = m ? m[0] : String(out).trim();
146
+ } catch (e) {
147
+ throw usageError('Could not read the clipboard: ' + e.message);
148
+ }
149
+ if (!token) throw usageError('The clipboard is empty.');
150
+ }
151
+
152
+ let customer = null;
153
+ // --cookies FILE / --cookies-stdin: importar desde un export del navegador.
154
+ // Netscape cookies.txt, JSON Cookie-Editor/EditThisCookie, header
155
+ // Cookie: o valor pelado. Solo se leen cookies de wetaca.com.
156
+ let cookieFileInput = null;
157
+ if (flags.cookies || flags['cookies-stdin']) {
158
+ try {
159
+ if (flags['cookies-stdin']) {
160
+ cookieFileInput = fs.readFileSync(0, 'utf8');
161
+ } else {
162
+ cookieFileInput = fs.readFileSync(String(flags.cookies).trim(), 'utf8');
163
+ }
164
+ } catch (e) {
165
+ throw usageError('Could not read the cookies file: ' + e.message);
166
+ }
167
+ }
168
+ if (cookieFileInput != null || flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN) {
169
+ // Import the refresh-token from the web (120-day cookie)
170
+ // and let /session/refresh mint the session tokens. No password is ever requested.
171
+ let rt;
172
+ if (cookieFileInput != null) {
173
+ rt = extractRefreshToken(cookieFileInput);
174
+ } else {
175
+ rt = String(flags['refresh-token'] || process.env.WETACA_REFRESH_TOKEN).trim();
176
+ }
177
+ if (!rt) {
178
+ throw new CliError(EXIT.AUTH,
179
+ 'The cookie export contains no "refresh-token" cookie from wetaca.com. ' +
180
+ 'Make sure to export the cookies while logged in to wetaca.com (the cookie is created on login).',
181
+ { reason: 'refresh_token_missing', suggested_commands: ['wetaca auth login --refresh-token VALOR'] });
182
+ }
183
+ saveProfile(ctx.profile, { refreshToken: rt });
184
+ try {
185
+ token = await sessionRefresh(rt, ctx.profile, ctx.debug);
186
+ viaRefresh = true;
187
+ } catch (e) {
188
+ throw new CliError(e.exitCode || EXIT.AUTH,
189
+ 'Could not refresh the session with that refresh-token. ' + e.message,
190
+ { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
191
+ }
192
+ const c = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
193
+ customer = c.customer;
194
+ } else if (token) {
195
+ // token supplied directly (advanced). Limpiar y validar llamando a la API de verdad
196
+ // (the test that matters is that `customer` responds; tokenIsValid is diagnostics only).
197
+ token = token.trim().replace(/^["']|["']$/g, '').replace(/^Bearer\s+/i, '');
198
+ if (!token) throw usageError('The token was empty.');
199
+ try {
200
+ const d = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
201
+ customer = d.customer;
202
+ } catch (e) {
203
+ let isValid = null;
204
+ try {
205
+ const v = await gql(Q.TOKEN_IS_VALID, { token }, { token, debug: ctx.debug });
206
+ isValid = v.tokenIsValid;
207
+ } catch { /* seguimos con el error original */ }
208
+ throw new CliError(EXIT.AUTH,
209
+ `The API rejected the token${isValid === false ? ' (tokenIsValid=false)' : ''}. ` +
210
+ 'Check that you copied ONLY what comes after "Bearer " in the authorization header ' +
211
+ '(without the word Bearer, without quotes). Original error: ' + e.message,
212
+ { reason: 'invalid_token' });
213
+ }
214
+ } else {
215
+ // Without --refresh-token or --token: prompt for it on the terminal (hidden). Accepts the
216
+ // refresh-token cookie (preferred, lasts 120 days) or a direct session JWT.
217
+ if (ctx.noInput || !process.stdin.isTTY) {
218
+ throw usageError('Without a terminal you need --refresh-token VALUE (a wetaca.com cookie, F12 → Application → Cookies), or --token VALUE / --token --clipboard.');
219
+ }
220
+ const pasted = await ask('Paste the refresh-token (or the session token) and press Enter: ', { hidden: true });
221
+ const v = (pasted || '').trim().replace(/^["']|["']$/g, '');
222
+ if (!v) throw usageError('No token was pasted.');
223
+ if (v.startsWith('eyJ')) {
224
+ token = v; // direct session JWT
225
+ } else {
226
+ saveProfile(ctx.profile, { refreshToken: v });
227
+ try {
228
+ token = await sessionRefresh(v, ctx.profile, ctx.debug);
229
+ viaRefresh = true;
230
+ } catch (e) {
231
+ throw new CliError(e.exitCode || EXIT.AUTH,
232
+ 'Could not refresh the session with that refresh-token. ' + e.message,
233
+ { reason: 'invalid_refresh_token', suggested_commands: ['wetaca auth login --token T'] });
234
+ }
235
+ }
236
+ try {
237
+ const c = await gql(Q.CUSTOMER, {}, { token, debug: ctx.debug });
238
+ customer = c.customer;
239
+ } catch (e) {
240
+ throw new CliError(EXIT.AUTH, 'The API rejected the token. Original error: ' + e.message,
241
+ { reason: 'invalid_token' });
242
+ }
243
+ }
244
+
245
+ // The session token and (if imported) the refresh-token are saved. NEVER the password.
246
+ saveProfile(ctx.profile, {
247
+ token,
248
+ email: customer?.email || null,
249
+ });
250
+ return {
251
+ ok: true, profile: ctx.profile, email: customer?.email || null,
252
+ via: viaRefresh ? 'refresh-token (auto-renewable ~120 days)' : 'session token (expires; renew it with --refresh-token)',
253
+ token: token.slice(0, 8) + '…',
254
+ };
255
+ }
256
+
257
+ export async function authStatus(args, flags, ctx) {
258
+ const token = getToken(ctx.profile);
259
+ if (!token) return { authenticated: false, profile: ctx.profile };
260
+ let authenticated = false, customer = null, err = null, tokenValid = null;
261
+ try {
262
+ const c = await gql(Q.CUSTOMER, {}, { profile: ctx.profile, debug: ctx.debug });
263
+ customer = c.customer;
264
+ authenticated = true;
265
+ } catch (e) {
266
+ err = e.message;
267
+ try {
268
+ const v = await gql(Q.TOKEN_IS_VALID, { token }, { profile: ctx.profile, debug: ctx.debug });
269
+ tokenValid = v.tokenIsValid;
270
+ } catch { /* el error de customer manda */ }
271
+ }
272
+ return { authenticated, profile: ctx.profile, customer, tokenValid, error: err };
273
+ }
274
+
275
+ export async function authLogout(args, flags, ctx) {
276
+ const token = getToken(ctx.profile);
277
+ if (token) { try { await gql(Q.LOGOUT, {}, { profile: ctx.profile, debug: ctx.debug }); } catch { /* best effort */ } }
278
+ const cfg = loadConfig();
279
+ if (cfg.profiles?.[ctx.profile]) { cfg.profiles[ctx.profile].token = null; saveConfig(cfg); }
280
+ const creds = loadCreds();
281
+ if (creds.profiles?.[ctx.profile]) { creds.profiles[ctx.profile].token = null; saveCreds(creds); }
282
+ return { ok: true, profile: ctx.profile };
283
+ }
284
+
285
+ // ---------- me ----------
286
+
287
+ export async function meShow(args, flags, ctx) {
288
+ const c = await gql(Q.CUSTOMER, {}, { profile: ctx.profile, debug: ctx.debug });
289
+ const s = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
290
+ const w = await gql(Q.WALLET, {}, { profile: ctx.profile, debug: ctx.debug });
291
+ const acc = s.subscriptionAccountByCustomer;
292
+ return {
293
+ customer: c.customer,
294
+ subscription: acc ? { id: acc.id, isActive: acc.isActive, cancelled: acc.cancelled, pausedUntil: acc.pausedUntil } : null,
295
+ walletBalance: w.walletBalance,
296
+ walletBalanceEur: w.walletBalance != null ? cents(w.walletBalance) : null,
297
+ };
298
+ }
299
+
300
+ // ---------- subscription ----------
301
+
302
+ export async function subShow(args, flags, ctx) {
303
+ const d = await gql(Q.SUBSCRIPTION_FULL, {}, { profile: ctx.profile, debug: ctx.debug });
304
+ const acc = d.subscriptionAccountByCustomer;
305
+ return {
306
+ id: acc.id,
307
+ isActive: acc.isActive,
308
+ cancelled: acc.cancelled,
309
+ pausedUntil: acc.pausedUntil,
310
+ dateCreated: acc.dateCreated,
311
+ delivery: acc.delivery,
312
+ pricing: acc.subscriptionAccountPricing,
313
+ pricingEur: {
314
+ toPay: cents(acc.subscriptionAccountPricing?.toPay),
315
+ shipping: cents(acc.subscriptionAccountPricing?.shipping),
316
+ },
317
+ recurring: acc.recurringSubscriptionType,
318
+ profiles: acc.profiles?.map((p) => ({ id: p.id, name: p.name, email: p.email, price: p.price, priceEur: cents(p.price), isActive: p.isActive })),
319
+ nextSuggestion: d.nextSuggestion,
320
+ };
321
+ }
322
+
323
+ export async function subPause(args, flags, ctx) {
324
+ const weeks = flags.weeks ? parseInt(flags.weeks, 10) : null;
325
+ if (flags.weeks && (!Number.isInteger(weeks) || weeks < 1)) {
326
+ throw usageError('--weeks must be an integer ≥ 1.');
327
+ }
328
+ const d0 = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
329
+ const acc = d0.subscriptionAccountByCustomer;
330
+ if (!acc?.isActive) throw new CliError(EXIT.API, 'The subscription is not active; nothing to pause.', { reason: 'not_active' });
331
+ const summary = `Pause subscription ${acc.id}${weeks ? ` for ${weeks} week(s)` : ' (indefinite pause)'}.`;
332
+ await confirm(flags, summary);
333
+ const d = await gql(Q.CANCEL_SUBSCRIPTION, {
334
+ subscriptionAccountId: acc.id, path: '/pausar', pausedWeeks: weeks, feedback: flags.feedback || null,
335
+ }, { profile: ctx.profile, debug: ctx.debug });
336
+ return { ok: true, paused: d.subscriptionAccount };
337
+ }
338
+
339
+ export async function subResume(args, flags, ctx) {
340
+ const d0 = await gql(Q.SUBSCRIBER_STATUS, {}, { profile: ctx.profile, debug: ctx.debug });
341
+ const acc = d0.subscriptionAccountByCustomer;
342
+ if (!acc) throw new CliError(EXIT.NOT_FOUND, 'No subscription account in this profile.', { reason: 'no_account' });
343
+ if (acc.isActive) return { ok: true, alreadyActive: true, subscriptionAccount: acc };
344
+ await confirm(flags, `Resume subscription ${acc.id}.`);
345
+ const d = await gql(Q.ACTIVATE_SUBSCRIPTION, { subscriptionAccountId: acc.id }, { profile: ctx.profile, debug: ctx.debug });
346
+ return { ok: true, subscriptionAccount: d.subscriptionAccount };
347
+ }
348
+
349
+ // ---------- suggestion (menu semanal) ----------
350
+
351
+ export async function sugShow(args, flags, ctx) {
352
+ const d = await gql(Q.NEXT_SUGGESTION, {}, { profile: ctx.profile, debug: ctx.debug });
353
+ const s = d.nextSuggestion;
354
+ if (!s) throw new CliError(EXIT.NOT_FOUND, 'No active suggestion for next week.', { reason: 'no_suggestion' });
355
+ return {
356
+ id: s.id,
357
+ skip: s.skip,
358
+ pausedAt: s.pausedAt,
359
+ validUntil: s.validUntil,
360
+ isBeingCharged: s.isBeingCharged,
361
+ deliveryWindow: s.delivery?.option ? { start: s.delivery.option.start, end: s.delivery.option.end } : null,
362
+ address: s.delivery?.address,
363
+ week: s.menuMetadata,
364
+ pricing: s.suggestionPricing,
365
+ pricingEur: {
366
+ toPay: cents(s.suggestionPricing?.toPay),
367
+ shipping: cents(s.suggestionPricing?.shipping),
368
+ profiles: cents(s.suggestionPricing?.profilesTotal?.toPay),
369
+ },
370
+ profiles: s.profileSuggestions?.map((ps) => ({
371
+ profileSuggestionId: ps.id,
372
+ profileId: ps.profileId,
373
+ skip: ps.skip,
374
+ hasChanges: ps.hasChanges,
375
+ products: ps.products,
376
+ productMap: ps.productMap,
377
+ })),
378
+ };
379
+ }
380
+
381
+ export async function sugPause(args, flags, ctx) {
382
+ const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
383
+ await confirm(flags, `Skip (pause) next week's delivery (suggestion ${sid}).`);
384
+ const d = await gql(Q.PAUSE_SUGGESTION, { suggestionId: sid, path: '/menu', feedback: flags.feedback || null }, { profile: ctx.profile, debug: ctx.debug });
385
+ return { ok: true, paused: d.paused };
386
+ }
387
+
388
+ export async function sugResume(args, flags, ctx) {
389
+ const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
390
+ await confirm(flags, `Resume next week's delivery (suggestion ${sid}).`);
391
+ const d = await gql(Q.RESUME_SUGGESTION, { suggestionId: sid }, { profile: ctx.profile, debug: ctx.debug });
392
+ return { ok: true, resumed: d.resumed };
393
+ }
394
+
395
+ // `suggestion edit --profile-suggestion ID --set "productId:qty,productId:qty"`
396
+ export async function sugEdit(args, flags, ctx) {
397
+ const psid = requireId(flags['profile-suggestion'] || flags.profileSuggestion, '--profile-suggestion');
398
+ if (!flags.set) throw usageError('Missing --set "productId:qty,...". Example: --set "abc123:2,def456:1".');
399
+ const productsInput = flags.set.split(',').map((pair) => {
400
+ const [id, qty] = pair.split(':').map((x) => x.trim());
401
+ if (!id || !qty) throw usageError(`Invalid pair in --set: '${pair}' (id:qty format).`);
402
+ const n = parseInt(qty, 10);
403
+ if (!Number.isInteger(n) || n < 0) throw usageError(`Invalid quantity in '${pair}'.`);
404
+ return { id, quantity: n };
405
+ });
406
+ const payload = { profileSuggestionId: psid, productsInput, resumeAccountSuggestion: flags.resume === undefined ? undefined : flags.resume === 'true' || flags.resume === true };
407
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'editProfileSuggestionMenu', variables: payload } };
408
+ await confirm(flags, `Change the menu of profile-suggestion ${psid} to: ${flags.set}.`);
409
+ const d = await gql(Q.EDIT_PROFILE_SUGGESTION_MENU, payload, { profile: ctx.profile, debug: ctx.debug });
410
+ return { ok: true, result: d.editProfileSuggestionProducts };
411
+ }
412
+
413
+ // ---------- deliveries / orders ----------
414
+
415
+ export async function deliveriesNext(args, flags, ctx) {
416
+ const d = await gql(Q.PENDING_DELIVERY, {}, { profile: ctx.profile, debug: ctx.debug });
417
+ return d;
418
+ }
419
+
420
+ export async function ordersList(args, flags, ctx) {
421
+ const limit = parseInt(flags.limit || '10', 10);
422
+ const offset = parseInt(flags.offset || '0', 10);
423
+ const d = await gql(Q.PREVIOUS_DELIVERIES, { limit, offset }, { profile: ctx.profile, debug: ctx.debug });
424
+ const rows = d.previousDeliveries.map((o) => ({ ...o, priceEur: cents(o.price) }));
425
+ return ctx.format === 'json' || ctx.format === 'jsonl' ? rows : { items: rows, limit, offset, count: rows.length };
426
+ }
427
+
428
+ export async function ordersShow(args, flags, ctx) {
429
+ const id = parseInt(requireId(args[0], '<order-id>'), 10);
430
+ if (!Number.isInteger(id)) throw usageError('The order id must be numeric.');
431
+ const d = await gql(Q.ORDER_DETAILS, { id }, { profile: ctx.profile, debug: ctx.debug });
432
+ return { ...d.order, priceEur: cents(d.order.price) };
433
+ }
434
+
435
+ export async function ordersCancel(args, flags, ctx) {
436
+ const id = parseInt(requireId(args[0], '<order-id>'), 10);
437
+ if (!Number.isInteger(id)) throw usageError('The order id must be numeric.');
438
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'cancelConfirmedOrder', variables: { orderId: id } } };
439
+ await confirm(flags, `Cancel order ${id} (takes effect on Wetaca).`);
440
+ const d = await gql(Q.CANCEL_ORDER, { orderId: id }, { profile: ctx.profile, debug: ctx.debug });
441
+ return { ok: true, cancelled: d.cancelConfirmedOrder, refundEur: cents(d.cancelConfirmedOrder?.amount) };
442
+ }
443
+
444
+ // ---------- addresses / vouchers ----------
445
+
446
+ export async function addrList(args, flags, ctx) {
447
+ const d = await gql(Q.ADDRESSES, {}, { profile: ctx.profile, debug: ctx.debug });
448
+ return d.addresses;
449
+ }
450
+
451
+ // Changes the delivery address: creates the new address (saveAddress) and assigns it
452
+ // to the subscription (editDeliveryAccountInfo) and to next week's suggestion
453
+ // (editSuggestionDelivery), keeping the current delivery option. Flow identical to the web's.
454
+ export async function addrSave(args, flags, ctx) {
455
+ const f = (k) => (flags[k] != null ? String(flags[k]).trim() : undefined);
456
+ const street = f('street'), number = f('number'), zipcode = f('zipcode'), city = f('city');
457
+ if (!street || !number || !zipcode || !city) {
458
+ throw usageError('Missing fields: --street, --number, --zipcode and --city are required ' +
459
+ '(optional: --floor, --notes, --firstname, --lastname, --phone; by default they are inherited from your current address).');
460
+ }
461
+ const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
462
+ const sub = cur.subscriptionAccountByCustomer;
463
+ const curAddr = sub?.delivery?.address || {};
464
+ const deliveryOptionId = sub?.delivery?.option?.id;
465
+ const suggestion = cur.nextSuggestion;
466
+ if (!deliveryOptionId) throw new CliError(EXIT.DRIFT, 'Could not read the current delivery option of your subscription.', { reason: 'no_delivery_option' });
467
+
468
+ const address = {
469
+ firstname: f('firstname') ?? curAddr.firstname,
470
+ lastname: f('lastname') ?? curAddr.lastname,
471
+ street,
472
+ number,
473
+ floor: f('floor') ?? curAddr.floor ?? null,
474
+ zipcode: parseInt(zipcode, 10),
475
+ city,
476
+ phone: f('phone') ?? curAddr.phone,
477
+ notes: f('notes') ?? curAddr.notes ?? null,
478
+ };
479
+ if (address.zipcode == null || Number.isNaN(address.zipcode)) throw usageError('--zipcode must be numeric.');
480
+ // NOTE: deliveryConfiguration does NOT carry "type" — the API returns 500 if you send it
481
+ // (tested live; the valid shape is {optionConfiguration: {addressId, deliveryOptionId}}).
482
+ const deliveryConfiguration = { optionConfiguration: { addressId: null, deliveryOptionId } };
483
+ const plan = {
484
+ saveAddress: address,
485
+ subscription: sub ? { mutation: 'editDeliveryAccountInfo', deliveryConfiguration } : null,
486
+ suggestion: suggestion ? { mutation: 'editSuggestionDelivery', suggestionId: suggestion.id, deliveryConfiguration } : null,
487
+ };
488
+ if (ctx.dryRun) return { dryRun: true, wouldSend: plan };
489
+ await confirm(flags, `Change your delivery address to ${street} ${number}${address.floor ? ', ' + address.floor : ''} (${address.zipcode} ${city}).`);
490
+ const saved = await gql(Q.SAVE_ADDRESS, { address }, { profile: ctx.profile, debug: ctx.debug });
491
+ const addressId = saved.saveAddress.id;
492
+ const deliveryConfiguration2 = { optionConfiguration: { addressId, deliveryOptionId } };
493
+ const subRes = sub ? await gql(Q.EDIT_SUBSCRIPTION_DELIVERY,
494
+ { subscriptionDeliveryInput: { deliveryConfiguration: deliveryConfiguration2 } },
495
+ { profile: ctx.profile, debug: ctx.debug }) : null;
496
+ const sugRes = suggestion ? await gql(Q.EDIT_SUGGESTION_DELIVERY,
497
+ { suggestionId: suggestion.id, suggestionDeliveryInput: { deliveryConfiguration: deliveryConfiguration2 } },
498
+ { profile: ctx.profile, debug: ctx.debug }) : null;
499
+ return {
500
+ ok: true,
501
+ address: saved.saveAddress,
502
+ phoneCarriedFromPrevious: !flags.phone && !!curAddr.phone,
503
+ subscriptionUpdated: subRes?.editDeliveryAccountInfo?.id === sub.id,
504
+ suggestionUpdated: sugRes?.editSuggestionDelivery?.id === suggestion.id,
505
+ };
506
+ }
507
+
508
+ // ---------- catalog ----------
509
+
510
+ // Weekly menu available for your zipcode (ids are the ones used by suggestion edit --set)
511
+ export async function menuList(args, flags, ctx) {
512
+ const zipcode = flags.zipcode != null ? parseInt(flags.zipcode, 10) : undefined;
513
+ const d = await gql(Q.SEGMENT_MENU, { zipcode, isSubscriptionIntent: true }, { profile: ctx.profile, debug: ctx.debug });
514
+ const m = d.segmentMenu;
515
+ if (!m) throw new CliError(EXIT.NOT_FOUND, 'No menu available for that postal code.', { reason: 'no_menu' });
516
+ return { week: m.week, year: m.year, dateFrom: m.dateFrom, dateTo: m.dateTo, dishes: m.dishes };
517
+ }
518
+
519
+ export async function dishShow(args, flags, ctx) {
520
+ const slug = args[0];
521
+ if (!slug) throw usageError('Usage: wetaca dish show <slug> (slugs come from `wetaca menu list`)');
522
+ const d = await gql(Q.DISH, { slug }, { profile: ctx.profile, debug: ctx.debug });
523
+ if (!d.dish) throw new CliError(EXIT.NOT_FOUND, `Dish '${slug}' does not exist.`, { reason: 'not_found' });
524
+ return d.dish;
525
+ }
526
+
527
+ // ---------- franja de entrega ----------
528
+
529
+ export async function delivOptions(args, flags, ctx) {
530
+ const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
531
+ const zipcode = flags.zipcode != null ? parseInt(flags.zipcode, 10) : cur.subscriptionAccountByCustomer?.delivery?.address?.zipcode;
532
+ if (!zipcode) throw usageError('Could not read your postal code; pass it with --zipcode.');
533
+ const d = await gql(Q.DELIVERY_OPTIONS, { zipcode }, { profile: ctx.profile, debug: ctx.debug });
534
+ const currentId = cur.subscriptionAccountByCustomer?.delivery?.option?.id;
535
+ return d.deliveryOptions.map((o) => ({ ...o, isCurrent: o.id === currentId, priceEur: cents(o.price) }));
536
+ }
537
+
538
+ // Changes the delivery slot (option) for the subscription and next week.
539
+ export async function delivSetOption(args, flags, ctx) {
540
+ const optionId = parseInt(requireId(args[0], '<option-id>'), 10);
541
+ if (!Number.isInteger(optionId)) throw usageError('The delivery window id must be numeric (they come from `wetaca deliveries options`).');
542
+ const cur = await gql(Q.DELIVERY_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
543
+ const sub = cur.subscriptionAccountByCustomer;
544
+ const suggestion = cur.nextSuggestion;
545
+ const curOption = sub?.delivery?.option;
546
+ if (!curOption) throw new CliError(EXIT.DRIFT, 'Could not read the current delivery window.', { reason: 'no_delivery_option' });
547
+ const opts = await gql(Q.DELIVERY_OPTIONS, { zipcode: sub?.delivery?.address?.zipcode }, { profile: ctx.profile, debug: ctx.debug });
548
+ const opt = (opts.deliveryOptions || []).find((o) => o.id === optionId);
549
+ if (!opt) throw new CliError(EXIT.NOT_FOUND,
550
+ `Delivery window ${optionId} is not available for your postal code. Available: ${(opts.deliveryOptions || []).map((o) => o.id).join(', ')}`,
551
+ { reason: 'option_not_available' });
552
+ const deliveryConfiguration = { optionConfiguration: { deliveryOptionId: optionId, addressId: sub?.delivery?.address?.id } };
553
+ const plan = {
554
+ option: opt,
555
+ subscription: { mutation: 'editDeliveryAccountInfo', deliveryConfiguration },
556
+ suggestion: suggestion ? { mutation: 'editSuggestionDelivery', suggestionId: suggestion.id, deliveryConfiguration } : null,
557
+ };
558
+ if (ctx.dryRun) return { dryRun: true, wouldSend: plan };
559
+ await confirm(flags, `Change your delivery window to ${fmtWindow(opt)} (was ${fmtWindow(curOption)}).`);
560
+ const subRes = await gql(Q.EDIT_SUBSCRIPTION_DELIVERY,
561
+ { subscriptionDeliveryInput: { deliveryConfiguration } }, { profile: ctx.profile, debug: ctx.debug });
562
+ const sugRes = suggestion ? await gql(Q.EDIT_SUGGESTION_DELIVERY,
563
+ { suggestionId: suggestion.id, suggestionDeliveryInput: { deliveryConfiguration } },
564
+ { profile: ctx.profile, debug: ctx.debug }) : null;
565
+ return {
566
+ ok: true,
567
+ option: opt,
568
+ subscriptionUpdated: subRes?.editDeliveryAccountInfo?.id === sub.id,
569
+ suggestionUpdated: sugRes?.editSuggestionDelivery?.id === suggestion.id,
570
+ };
571
+ }
572
+
573
+ // ---------- perfiles ----------
574
+
575
+ export async function profilesList(args, flags, ctx) {
576
+ const d = await gql(Q.PROFILES, {}, { profile: ctx.profile, debug: ctx.debug });
577
+ const s = d.subscriptionAccountByCustomer;
578
+ return { subscriptionId: s.id, isActive: s.isActive, pausedUntil: s.pausedUntil, profiles: s.profiles };
579
+ }
580
+
581
+ async function resolveProfileId(args) {
582
+ const key = requireId(args[0], '<profile-id|name>');
583
+ const d = await gql(Q.PROFILES, {}, {});
584
+ const profiles = d.subscriptionAccountByCustomer?.profiles || [];
585
+ const p = profiles.find((x) => x.id === key || x._id === key
586
+ || x.name?.toLowerCase() === key.toLowerCase());
587
+ if (!p) throw new CliError(EXIT.NOT_FOUND,
588
+ `Profile '${key}' does not exist. Profiles: ${profiles.map((x) => `${x.name} (${x.id})`).join(', ')}`,
589
+ { reason: 'not_found' });
590
+ return p;
591
+ }
592
+
593
+ export async function profilesPause(args, flags, ctx) {
594
+ const p = await resolveProfileId(args);
595
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'pauseProfile', profileId: p.id } };
596
+ await confirm(flags, `Pause profile '${p.name}' (stops receiving tuppers for that profile).`);
597
+ const d = await gql(Q.PAUSE_PROFILE, { profileId: p.id }, { profile: ctx.profile, debug: ctx.debug });
598
+ return { ok: true, profile: d.pauseProfile };
599
+ }
600
+
601
+ export async function profilesResume(args, flags, ctx) {
602
+ const p = await resolveProfileId(args);
603
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'resumeProfile', profileId: p.id } };
604
+ await confirm(flags, `Resume profile '${p.name}'.`);
605
+ const d = await gql(Q.RESUME_PROFILE, { profileId: p.id }, { profile: ctx.profile, debug: ctx.debug });
606
+ return { ok: true, profile: d.resumeProfile };
607
+ }
608
+
609
+ // Deletes a saved address. Protection: if it is in use by the subscription or
610
+ // next week, it requires assigning another one first (addresses save).
611
+ export async function addrRemove(args, flags, ctx) {
612
+ const id = parseInt(requireId(args[0], '<address-id>'), 10);
613
+ if (!Number.isInteger(id)) throw usageError('The address id must be numeric (they come from `wetaca addresses list`).');
614
+ const d0 = await gql(Q.ADDRESSES, {}, { profile: ctx.profile, debug: ctx.debug });
615
+ const a = (d0.addresses || []).find((x) => x.id === id);
616
+ if (!a) throw new CliError(EXIT.NOT_FOUND, `Address ${id} does not exist.`, { reason: 'not_found' });
617
+ if (a.isSubscriptionAddress || a.isSuggestionAddress) {
618
+ throw usageError(`Address ${id} (${a.street} ${a.number}) is in use; first assign another with \`wetaca addresses save\`.`);
619
+ }
620
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'removeAddress', addressId: id } };
621
+ await confirm(flags, `Delete address ${id} (${a.street} ${a.number}, ${a.zipcode} ${a.city}).`);
622
+ const d = await gql(Q.REMOVE_ADDRESS, { addressId: id }, { profile: ctx.profile, debug: ctx.debug });
623
+ return { ok: true, removed: d.removeAddress?.id === id, addressId: id };
624
+ }
625
+
626
+ export async function vouchersList(args, flags, ctx) {
627
+ const d = await gql(Q.VOUCHERS, {}, { profile: ctx.profile, debug: ctx.debug });
628
+ return d.vouchers.map((v) => ({
629
+ ...v,
630
+ discountEur: v.discount?.price != null ? cents(v.discount.price) : null,
631
+ subscriptionDiscountEur: v.subscriptionDiscount?.price != null ? cents(v.subscriptionDiscount.price) : null,
632
+ }));
633
+ }
634
+
635
+ export async function walletShow(args, flags, ctx) {
636
+ const d = await gql(Q.WALLET, {}, { profile: ctx.profile, debug: ctx.debug });
637
+ return { balance: d.walletBalance, balanceEur: cents(d.walletBalance) };
638
+ }
639
+
640
+ // ---------- config ----------
641
+
642
+ export async function configCmd(verb, args, flags, ctx) {
643
+ if (verb === 'path') return { config: configPath(), credentials: credentialsPath() };
644
+ const cfg = loadConfig();
645
+ if (verb === 'list') return { defaultProfile: cfg.defaultProfile, config: { ...cfg.profiles, _meta: { redacted: true } }, note: 'tokens are not shown' };
646
+ if (verb === 'get') {
647
+ const key = args[0];
648
+ if (!key) throw usageError('Missing key: config get <dotted.path>');
649
+ const val = key.split('.').reduce((acc, k) => acc?.[k], cfg);
650
+ return { key, value: val === undefined ? null : (String(key).endsWith('token') ? '***' : val) };
651
+ }
652
+ if (verb === 'set') {
653
+ const [key, ...rest] = args;
654
+ if (!key || rest.length === 0) throw usageError('Usage: config set <key> <value>');
655
+ if (key.endsWith('token')) throw usageError('The token is managed with `wetaca auth login --token`.');
656
+ const value = rest.join(' ') === 'true' ? true : rest.join(' ') === 'false' ? false : rest.join(' ');
657
+ const parts = key.split('.');
658
+ let obj = cfg;
659
+ for (let i = 0; i < parts.length - 1; i++) obj = (obj[parts[i]] ??= {});
660
+ obj[parts[parts.length - 1]] = value;
661
+ saveConfig(cfg);
662
+ return { ok: true, key, value };
663
+ }
664
+ throw usageError(`Config verbs: path | list | get | set`);
665
+ }
666
+
667
+ // ---------- doctor ----------
668
+
669
+ export async function doctor(args, flags, ctx) {
670
+ const checks = [];
671
+ const push = (name, ok, detail) => checks.push({ check: name, ok, detail });
672
+
673
+ const nodeOk = parseInt(process.versions.node.split('.')[0], 10) >= 18;
674
+ push('node >= 18', nodeOk, process.versions.node);
675
+
676
+ let apiOk = false, apiDetail;
677
+ try {
678
+ const res = await fetch(process.env.WETACA_API_URL || 'https://api.wetaca.com/graphql', {
679
+ method: 'POST', headers: { 'Content-Type': 'application/json' },
680
+ body: JSON.stringify({ query: 'query { __typename }' }),
681
+ });
682
+ const j = await res.json();
683
+ apiOk = res.ok && !!j.data?.__typename;
684
+ apiDetail = `HTTP ${res.status}`;
685
+ } catch (e) { apiDetail = `no connection: ${e.cause?.code || e.message}`; }
686
+ push('api.wetaca.com reachable', apiOk, apiDetail);
687
+
688
+ const token = getToken(ctx.profile);
689
+ push('session present', !!token, token ? 'token configured' : 'no token — wetaca auth login');
690
+ if (token) {
691
+ try {
692
+ const d = await gql(Q.TOKEN_IS_VALID, { token }, { profile: ctx.profile, debug: ctx.debug });
693
+ push('token valid', d.tokenIsValid === true, `tokenIsValid=${d.tokenIsValid}`);
694
+ } catch (e) {
695
+ push('token valid', false, e.message);
696
+ }
697
+ }
698
+ push('config directory', true, configDir());
699
+ return { ok: checks.every((c) => c.ok), checks };
700
+ }