wetaca-cli 0.2.3 → 0.2.5

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/AGENTS.md ADDED
@@ -0,0 +1,31 @@
1
+ # AGENTS.md
2
+
3
+ Guidance for AI coding agents (Claude Code, Codex, Cursor, Hermes, OpenCode, Jules, ...) working in this repository — and a pointer for agents that help the *user* manage their Wetaca account with the installed CLI.
4
+
5
+ ## Managing a Wetaca account with wetaca-cli
6
+
7
+ If your goal is to operate the user's Wetaca account (menu, subscription, deliveries, orders, vouchers), **do not read this repo's source first**. Run the embedded agent guide:
8
+
9
+ ```
10
+ wetaca skills get wetaca-usage
11
+ ```
12
+
13
+ That output is the canonical, version-matched contract: output formats, exit codes, command list, confirmation rules and typical flows. If `wetaca` is not installed: `npm install -g wetaca-cli`.
14
+
15
+ Non-negotiable rules when acting on a real account:
16
+
17
+ 1. Reads (`suggestion show`, `orders list`, ...) are safe; run them freely.
18
+ 2. Mutations require an explicit summary → confirmation. In non-interactive runs pass `--yes` ONLY when the user asked for that exact operation.
19
+ 3. Prefer `--dry-run` before any mutation that supports it.
20
+ 4. Never touch payments (the CLI cannot either).
21
+
22
+ ## Working on this codebase
23
+
24
+ - Zero-dependency Node ESM (>=18). Do not add npm dependencies.
25
+ - Layout: `bin/wetaca.js` (arg parsing, dispatch, help), `src/lib.js` (config, GraphQL client, errors, output), `src/commands.js` (command implementations), `src/queries.js` (GraphQL operations), `src/guide.js` (embedded agent guide — single source for `docs/agent-guide.md`, regenerate with `node bin/wetaca.js skills get wetaca-usage > docs/agent-guide.md`).
26
+ - GraphQL reference operations live in `docs/api-operations/` (extracted from wetaca.com's production bundle; `extract-gql.mjs` re-extracts them).
27
+ - Contract: every command returns JSON on stdout (pretty/jsonl optional), errors as JSON on stderr with `--error-format json`, stable exit codes (0 ok, 1 unexpected, 2 usage, 3 auth, 4 network, 5 not found, 6 API, 7 contract drift). See `docs/cli-spec.md`.
28
+ - Mutations must follow the existing pattern: build payload → honor `--dry-run` → `confirm(flags, summary)` unless `--yes` → call `gql()`.
29
+ - After changing `src/guide.js`, regenerate `docs/agent-guide.md` (they must stay identical).
30
+ - Check syntax before committing: `node --check` on every touched file. CI runs the same checks plus smoke tests and cookie-parser tests.
31
+ - Releases: `npm version patch && git push --follow-tags`. The GitHub Actions `Publish to npm` workflow stages the package (`npm stage publish`, OIDC trusted publishing, no token); a maintainer approves it with `npm stage approve <id> --otp <code>`.
package/README.md CHANGED
@@ -26,7 +26,17 @@ npm install -g wetaca-cli # from npm
26
26
  wetaca doctor
27
27
  ```
28
28
 
29
- Or from the repo: `npm install -g .`
29
+ Or from this repo: `npm install -g .`
30
+
31
+ ## For AI agents
32
+
33
+ Point your agent at this repo and it will find `AGENTS.md` (Claude Code, Codex, Cursor, OpenCode, Jules, Hermes all read it automatically). The canonical contract for agents is embedded in the binary:
34
+
35
+ ```
36
+ wetaca skills get wetaca-usage
37
+ ```
38
+
39
+ A portable skill file is also available at [`skill/SKILL.md`](skill/SKILL.md) for platforms with skill directories (Hermes: `hermes skills install https://raw.githubusercontent.com/gorgueugr/wetaca-cli/master/skill/SKILL.md`).
30
40
 
31
41
  ## Get started
32
42
 
@@ -71,6 +81,7 @@ wetaca skills get wetaca-usage
71
81
  | [Specification](docs/cli-spec.md) | every command, flag, exit code and GraphQL operation |
72
82
  | [Extracted operations](docs/api-operations/) | the ~190 GraphQL documents from Wetaca's website |
73
83
  | [Agent guide](docs/agent-guide.md) | `wetaca skills get wetaca-usage` |
84
+ | [Agent skill](skill/SKILL.md) | portable SKILL.md for skill hubs (Hermes, Claude Code, OpenCode...) |
74
85
 
75
86
  ## Good to know
76
87
 
package/bin/wetaca.js CHANGED
@@ -31,7 +31,8 @@ COMMANDS
31
31
  optional --notes --firstname --lastname --phone (inherit the current ones by default)
32
32
  --dry-run shows the exact plan before executing
33
33
  remove <id>: deletes an unused address
34
- vouchers list
34
+ vouchers list | current | apply <CODE> | skip vouchers and applying them to next week
35
+ giftcards show | redeem <CODE> gift cards: limits and redeem into your wallet
35
36
  wallet show
36
37
  config path | list | get <k> | set <k> <v>
37
38
  doctor diagnostics (node, network, session)
@@ -194,7 +195,15 @@ async function main() {
194
195
  else throw usageUnknown(noun, verb);
195
196
  break;
196
197
  case 'vouchers':
197
- if (verb === 'list') result = await C.vouchersList(args, flags, ctx);
198
+ if (verb === 'list' || verb === undefined) result = await C.vouchersList(args, flags, ctx);
199
+ else if (verb === 'apply') result = await C.vouchersApply(args, flags, ctx);
200
+ else if (verb === 'skip') result = await C.vouchersApply(['skip'], flags, ctx);
201
+ else if (verb === 'current') result = await C.vouchersCurrent(args, flags, ctx);
202
+ else throw usageUnknown(noun, verb);
203
+ break;
204
+ case 'giftcards':
205
+ if (verb === 'show' || verb === undefined) result = await C.giftShow(args, flags, ctx);
206
+ else if (verb === 'redeem') result = await C.giftRedeem(args, flags, ctx);
198
207
  else throw usageUnknown(noun, verb);
199
208
  break;
200
209
  case 'wallet':
@@ -1,71 +1,78 @@
1
- # wetaca-cli — guía para agentes IA
1
+ # wetaca-cli — guide for AI agents
2
2
 
3
- Gestiona la cuenta de Wetaca (suscripción de comida semanal) del usuario desde el terminal.
4
- Todo comando devuelve JSON en stdout por defecto; los errores van a stderr.
3
+ Manage the user's Wetaca account (weekly meal subscription) from the terminal.
4
+ Every command returns JSON on stdout by default; errors go to stderr.
5
5
 
6
- ## Antes de empezar
6
+ ## Before you start
7
7
 
8
- 1. Ejecuta `wetaca doctor` para verificar node, conectividad y sesión.
9
- 2. `wetaca auth status` dice si hay sesión válida. Si no la hay:
10
- - `wetaca auth login --cookies cookies.txt` (export con la extensión Cookie-Editor sobre wetaca.com logueado) o `--refresh-token COOKIE` (cookie de wetaca.com, dura ~120 días; el CLI renueva el token solo). Sin contraseña.
11
- - `wetaca auth login --token T` o `--token --clipboard`: token copiado de la cabecera
12
- `authorization: Bearer …` de cualquier petición a api.wetaca.com en las DevTools del
13
- usuario (F12 → Network). Es la vía si su cuenta entra con Google.
14
- No pidas al usuario la contraseña de Google ni automatices su navegador para el login.
8
+ 1. Run `wetaca doctor` to check node, connectivity and session.
9
+ 2. `wetaca auth status` tells you whether there is a valid session. If there isn't:
10
+ - `wetaca auth login --cookies cookies.txt` (export with the Cookie-Editor extension on wetaca.com while logged in) or `--refresh-token COOKIE` (a wetaca.com cookie, lasts ~120 days; the CLI renews the token on its own). No password involved.
11
+ - `wetaca auth login --token T` or `--token --clipboard`: token copied from the
12
+ `authorization: Bearer *** header of any request to api.wetaca.com in the
13
+ user's DevTools (F12 → Network). This is the way to go if their account logs in with Google.
14
+ Never ask the user for their Google password and never automate their browser for the login.
15
15
 
16
- ## Contrato de salida
16
+ ## Output contract
17
17
 
18
- - stdout: JSON (`--format pretty` para humanos, `jsonl` para listas línea a línea).
19
- - `--error-format json`: envoltorio de error { error: { code, category, reason, retryable, message, suggested_commands } }.
20
- - Exit codes estables: 0 ok · 1 inesperado · 2 uso/validación/confirmación denegada · 3 auth ·
21
- 4 red · 5 no encontrado · 6 la API rechazó la operación · 7 deriva de contrato (schema cambiado).
22
- - `reason: "auth_required"` → nada que reintentar; el usuario debe hacer login.
23
- - `reason: "contract_drift"` → no reinventes la query; abre issue en el repo.
18
+ - stdout: JSON (`--format pretty` for humans, `jsonl` for lists, one line each).
19
+ - `--error-format json`: error wrapper { error: { code, category, reason, retryable, message, suggested_commands } }.
20
+ - Stable exit codes: 0 ok · 1 unexpected · 2 usage/validation/confirmation denied · 3 auth ·
21
+ 4 network · 5 not found · 6 the API rejected the operation · 7 contract drift (schema changed).
22
+ - `reason: "auth_required"` → nothing to retry; the user must log in.
23
+ - `reason: "contract_drift"` → don't reinvent the query; open an issue on the repo.
24
24
 
25
- ## Reglas para operaciones con efectos reales
25
+ ## Rules for operations with real effects
26
26
 
27
- 1. Nada cambia la cuenta sin confirmación: sin terminal, exige `--yes`. Pasa `--yes` SOLO cuando
28
- el usuario pidió exactamente esa operación y vio el resumen.
29
- 2. Usa `--dry-run` en `suggestion edit` y `orders cancel` para mostrar qué se enviaría, antes de pedir confirmación.
30
- 3. `suggestion pause` salta la entrega de la semana próxima (la semana ya cobrada NO se toca).
31
- `subscription pause --weeks N` pausa la suscripción N semanas (cancelación temporal);
32
- `subscription resume` la reactiva.
33
- 4. `orders cancel <id>` cancela un pedido confirmado y devuelve el importe. Ids: `deliveries next`
34
- (pedidos pendientes) y `orders list` (histórico).
35
- 5. Nunca gestiones pagos: wetaca-cli no toca tarjetas ni pagos pendientes de Redsys/PayPal.
36
- Si `nextPaymentPendingOrder` no es null, dilo al usuario y que lo pague en wetaca.com.
27
+ 1. Nothing changes the account without confirmation: without a terminal, `--yes` is required. Pass `--yes` ONLY when
28
+ the user asked for exactly that operation and saw the summary.
29
+ 2. Use `--dry-run` on `suggestion edit` and `orders cancel` to show what would be sent, before asking for confirmation.
30
+ 3. `suggestion pause` skips next week's delivery (the already-billed week is NOT touched).
31
+ `subscription pause --weeks N` pauses the subscription for N weeks (temporary cancellation);
32
+ `subscription resume` reactivates it.
33
+ 4. `orders cancel <id>` cancels a confirmed order and refunds the amount. Ids: `deliveries next`
34
+ (pending orders) and `orders list` (history).
35
+ 5. Never manage payments: wetaca-cli does not touch cards or pending Redsys/PayPal payments.
36
+ If `nextPaymentPendingOrder` is not null, tell the user and have them pay on wetaca.com.
37
37
 
38
- ## Comandos
38
+ ## Commands
39
39
 
40
40
  wetaca auth login [--refresh-token COOKIE | --token T] | status | logout
41
- wetaca me resumen: cliente + suscripción + cartera
41
+ wetaca me summary: customer + subscription + wallet
42
42
  wetaca subscription show | pause [--weeks N] [--feedback S] | resume
43
- wetaca suggestion show menú de la semana próxima por perfil, precios, ventana de entrega
44
- wetaca suggestion pause | resume saltar / reactivar la semana próxima
45
- wetaca suggestion edit --profile-suggestion ID --set "productId:cant,..." [--dry-run]
46
- wetaca deliveries next sugerencias y pedidos pendientes (ids para orders/cancel)
43
+ wetaca suggestion show next week's menu per profile, prices, delivery window
44
+ wetaca suggestion pause | resume skip / reactivate next week
45
+ wetaca suggestion edit --profile-suggestion ID --set "productId:qty,..." [--dry-run]
46
+ wetaca deliveries next suggestions and pending orders (ids for orders/cancel)
47
47
  wetaca orders list [--limit N] | show <id> | cancel <id> [--dry-run]
48
- wetaca menu list platos de la semana (ids para suggestion edit)
49
- wetaca dish show <slug> detalle/ingredientes de un plato
50
- wetaca deliveries options franjas de entrega disponibles para tu CP
51
- wetaca deliveries set-option <id> --dry-run cambia la franja (revisa y repite con --yes)
52
- wetaca profiles list tus perfiles y su menú
53
- wetaca profiles pause <id|nombre> pausa un perfil (dry-run antes)
48
+ wetaca menu list dishes of the week (ids for suggestion edit)
49
+ wetaca dish show <slug> details/ingredients of a dish
50
+ wetaca deliveries options delivery slots available for your zip code
51
+ wetaca deliveries set-option <id> --dry-run changes the slot (review and repeat with --yes)
52
+ wetaca profiles list your profiles and their menu
53
+ wetaca profiles pause <id|name> pauses a profile (dry-run first)
54
54
  wetaca addresses list
55
- wetaca addresses save --street C --number N [--floor F] --zipcode CP --city CIUDAD --dry-run
56
- (revisa el plan; repite con --yes; opcional --notes --firstname --lastname --phone)
57
- wetaca addresses remove <id> borra una dirección no en uso
55
+ wetaca addresses save --street C --number N [--floor F] --zipcode ZIP --city CITY --dry-run
56
+ (review the plan; repeat with --yes; optional --notes --firstname --lastname --phone)
57
+ wetaca addresses remove <id> deletes an address not in use
58
58
  wetaca vouchers list
59
+ wetaca vouchers current voucher applied to next week (if any)
60
+ wetaca vouchers apply <CODE> apply a voucher to next week (--dry-run first, then --yes)
61
+ wetaca vouchers skip explicitly use no voucher next week (WARNING: the API
62
+ implements this as skipVoucher=true, which ALSO pauses
63
+ next week's delivery — same effect as suggestion pause.
64
+ Revert with: wetaca suggestion resume)
65
+ wetaca giftcards show | redeem <CODE> gift card limits / redeem into wallet
59
66
  wetaca wallet
60
67
  wetaca config path | list | get <k> | set <k> <v>
61
68
  wetaca doctor
62
- wetaca skills get wetaca-usage esta guía
69
+ wetaca skills get wetaca-usage this guide
63
70
 
64
- ## Flujos típicos
71
+ ## Typical flows
65
72
 
66
- - "¿Qué toca esta semana?": `wetaca suggestion show --format pretty`
67
- - "Esta semana no quiero arroz": `suggestion show` → localiza el plato y su `productSuggestionId`
68
- (`profileSuggestionId`) y `productId` → `suggestion edit --profile-suggestion ID --set "..." --dry-run`
69
- → muestra el plan → confirma → ejecuta con `--yes`.
70
- - "Vacaciones dos semanas": `subscription pause --weeks 2` (resumen → --yes) y luego `subscription resume`.
71
- - "Cancela el pedido de mañana": `deliveries next` → `orders cancel <id>`.
73
+ - "What's on this week?": `wetaca suggestion show --format pretty`
74
+ - "I don't want rice this week": `suggestion show` → locate the dish and its `productSuggestionId`
75
+ (`profileSuggestionId`) and `productId` → `suggestion edit --profile-suggestion ID --set "..." --dry-run`
76
+ → show the plan → confirm → run with `--yes`.
77
+ - "Vacation for two weeks": `subscription pause --weeks 2` (summary → --yes) and then `subscription resume`.
78
+ - "Cancel tomorrow's order": `deliveries next` → `orders cancel <id>`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "wetaca-cli",
3
- "version": "0.2.3",
3
+ "version": "0.2.5",
4
4
  "description": "Manage your Wetaca from the terminal: subscription, weekly menu, deliveries and orders. Built for people and AI agents.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -10,6 +10,8 @@
10
10
  "bin",
11
11
  "src",
12
12
  "docs",
13
+ "skill",
14
+ "AGENTS.md",
13
15
  "README.md",
14
16
  "LICENSE"
15
17
  ],
package/skill/SKILL.md ADDED
@@ -0,0 +1,39 @@
1
+ ---
2
+ name: wetaca-usage
3
+ description: Use when the user asks about Wetaca meals or deliveries.
4
+ version: 0.2.4
5
+ author: Jorge Soler Padial (https://github.com/gorgueugr)
6
+ license: MIT
7
+ metadata:
8
+ hermes:
9
+ tags: [wetaca, cli, account-management]
10
+ ---
11
+
12
+ # wetaca-cli — agent guide
13
+
14
+ Run the embedded, version-matched guide (source of truth, kept in sync with the installed binary):
15
+
16
+ ```
17
+ wetaca skills get wetaca-usage
18
+ ```
19
+
20
+ If `wetaca` is not installed: `npm install -g wetaca-cli` (requires Node >= 18).
21
+
22
+ ## When to Use
23
+
24
+ - The user asks about their Wetaca account: weekly menu, subscription, deliveries, orders, vouchers, gift cards, wallet or addresses.
25
+ - The user wants to change next week's menu, skip a week, pause the subscription, cancel an order or apply a voucher.
26
+
27
+ ## Contract
28
+
29
+ Every command returns JSON on stdout by default (`--format pretty` for humans); errors go to stderr as JSON with `--error-format json`; stable exit codes (0 ok · 1 unexpected · 2 usage/confirmation · 3 auth · 4 network · 5 not found · 6 API rejected · 7 contract drift).
30
+
31
+ ## Golden rules
32
+
33
+ 1. Reads are safe. Run them freely.
34
+ 2. Mutations need a summary shown to the user; pass `--yes` only for an explicitly requested operation.
35
+ 3. Use `--dry-run` on `suggestion edit`, `addresses save`, `deliveries set-option`, `orders cancel` before any real run.
36
+ 4. Never touch payments — the CLI does not either.
37
+ 5. `reason: "auth_required"` → the user must run `wetaca auth login` (cookie-based; no password involved).
38
+
39
+ Project source: https://github.com/gorgueugr/wetaca-cli
package/src/commands.js CHANGED
@@ -3,7 +3,7 @@ import readline from 'node:readline/promises';
3
3
  import child_process from 'node:child_process';
4
4
  import fs from 'node:fs';
5
5
  import {
6
- CliError, usageError, EXIT, gql, cents, fmtDate, emit,
6
+ CliError, usageError, EXIT, gql, cents, fmtDate, fmtWindow, emit,
7
7
  getToken, loadConfig, saveConfig, saveProfile, configPath, configDir,
8
8
  loadCreds, saveCreds, credentialsPath, sessionRefresh,
9
9
  } from './lib.js';
@@ -401,7 +401,9 @@ export async function sugEdit(args, flags, ctx) {
401
401
  if (!id || !qty) throw usageError(`Invalid pair in --set: '${pair}' (id:qty format).`);
402
402
  const n = parseInt(qty, 10);
403
403
  if (!Number.isInteger(n) || n < 0) throw usageError(`Invalid quantity in '${pair}'.`);
404
- return { id, quantity: n };
404
+ const pid = parseInt(id, 10); // the API declares productsInput[].id as Int (ModelId)
405
+ if (!Number.isInteger(pid) || pid <= 0) throw usageError(`Invalid product id in '${pair}' (must be numeric, from \`wetaca suggestion show\`).`);
406
+ return { id: pid, quantity: n };
405
407
  });
406
408
  const payload = { profileSuggestionId: psid, productsInput, resumeAccountSuggestion: flags.resume === undefined ? undefined : flags.resume === 'true' || flags.resume === true };
407
409
  if (ctx.dryRun) return { dryRun: true, wouldSend: { query: 'editProfileSuggestionMenu', variables: payload } };
@@ -637,6 +639,60 @@ export async function walletShow(args, flags, ctx) {
637
639
  return { balance: d.walletBalance, balanceEur: cents(d.walletBalance) };
638
640
  }
639
641
 
642
+ // ---------- vouchers apply / gift cards ----------
643
+
644
+ // `vouchers apply CODE` / `vouchers skip` — applies (or explicitly skips) a voucher
645
+ // on next week's suggestion. NOTE: the API implements `skip` as skipVoucher=true,
646
+ // which ALSO sets suggestion.skip=true (pauses next week's delivery). Verified live
647
+ // 2026-10-29 — `vouchers skip` == `suggestion pause` + explicit no-voucher.
648
+ // Revert with `suggestion resume`.
649
+ export async function vouchersApply(args, flags, ctx) {
650
+ const skip = args[0] === 'skip' || flags.skip === true;
651
+ const code = skip ? undefined : args[0];
652
+ if (!skip && !code) throw usageError("Usage: vouchers apply <CODE> | vouchers skip (explicitly don't use a voucher).");
653
+ const sid = flags.suggestion || await nextSuggestionId(ctx.profile, ctx.debug);
654
+ const payload = { voucherCode: skip ? undefined : code, skipVoucher: skip, suggestionId: sid };
655
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'assignNextSuggestionVoucher', variables: payload } };
656
+ await confirm(flags, skip
657
+ ? `Skip voucher on next week's delivery (suggestion ${sid}). WARNING: the API also pauses next week's delivery (skipVoucher=true sets suggestion.skip). Revert with: wetaca suggestion resume.`
658
+ : `Apply voucher ${code} to next week's delivery (suggestion ${sid}).`);
659
+ const d = await gql(Q.ASSIGN_NEXT_SUGGESTION_VOUCHER, payload, { profile: ctx.profile, debug: ctx.debug });
660
+ const r = d.assignNextSuggestionVoucher || {};
661
+ return {
662
+ ok: true,
663
+ applied: r.appliedVoucher ? { code: r.appliedVoucher.code, discount: r.appliedVoucher.appliedDiscount } : null,
664
+ skipped: r.skipVoucher === true,
665
+ suggestionId: sid,
666
+ };
667
+ }
668
+
669
+ // `vouchers current` — what voucher (if any) is applied to next week's suggestion.
670
+ export async function vouchersCurrent(args, flags, ctx) {
671
+ const d = await gql(Q.NEXT_SUGGESTION_APPLIED_VOUCHER, {}, { profile: ctx.profile, debug: ctx.debug });
672
+ const v = d.nextSuggestion?.appliedVoucher;
673
+ if (!v) return { applied: false, suggestionId: d.nextSuggestion?.id ?? null };
674
+ return { applied: true, suggestionId: d.nextSuggestion.id, code: v.code, discount: v.appliedDiscount };
675
+ }
676
+
677
+ // `giftcards show` — allowed min/max amounts.
678
+ export async function giftShow(args, flags, ctx) {
679
+ const d = await gql(Q.GIFT_CARDS_CONFIG, {}, { profile: ctx.profile, debug: ctx.debug });
680
+ const c = d.giftCardsConfiguration || {};
681
+ return { minAmount: c.minAmount, maxAmount: c.maxAmount };
682
+ }
683
+
684
+ // `giftcards redeem CODE` — adds the gift card balance to your wallet.
685
+ export async function giftRedeem(args, flags, ctx) {
686
+ const code = args[0];
687
+ if (!code) throw usageError('Usage: giftcards redeem <CODE>.');
688
+ const payload = { code: String(code).trim() };
689
+ if (ctx.dryRun) return { dryRun: true, wouldSend: { mutation: 'redeemGiftCard', variables: payload } };
690
+ await confirm(flags, `Redeem gift card ${payload.code} into your wallet.`);
691
+ const d = await gql(Q.REDEEM_GIFT_CARD, payload, { profile: ctx.profile, debug: ctx.debug });
692
+ const r = d.redeemGiftCard || {};
693
+ return { ok: true, code: r.code, amount: r.amount, amountEur: cents(r.amount) };
694
+ }
695
+
640
696
  // ---------- config ----------
641
697
 
642
698
  export async function configCmd(verb, args, flags, ctx) {
package/src/guide.js CHANGED
@@ -57,6 +57,13 @@ Every command returns JSON on stdout by default; errors go to stderr.
57
57
  (review the plan; repeat with --yes; optional --notes --firstname --lastname --phone)
58
58
  wetaca addresses remove <id> deletes an address not in use
59
59
  wetaca vouchers list
60
+ wetaca vouchers current voucher applied to next week (if any)
61
+ wetaca vouchers apply <CODE> apply a voucher to next week (--dry-run first, then --yes)
62
+ wetaca vouchers skip explicitly use no voucher next week (WARNING: the API
63
+ implements this as skipVoucher=true, which ALSO pauses
64
+ next week's delivery — same effect as suggestion pause.
65
+ Revert with: wetaca suggestion resume)
66
+ wetaca giftcards show | redeem <CODE> gift card limits / redeem into wallet
60
67
  wetaca wallet
61
68
  wetaca config path | list | get <k> | set <k> <v>
62
69
  wetaca doctor
package/src/lib.js CHANGED
@@ -173,13 +173,20 @@ async function rawRequest(query, variables, tok, debug) {
173
173
  throw e;
174
174
  }
175
175
  throw new CliError(EXIT.API, `The API responded with HTTP ${res.status}`,
176
- { reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429 });
176
+ { reason: 'http_' + res.status, retryable: res.status >= 500 || res.status === 429, httpStatus: res.status });
177
177
  }
178
178
  let body;
179
179
  try { body = await res.json(); } catch {
180
180
  throw new CliError(EXIT.DRIFT, 'The API returned a non-JSON response (possible contract change).',
181
181
  { reason: 'contract_drift', retryable: false });
182
182
  }
183
+ // GraphQL validation errors can hide behind HTTP 500: surface them as an API error
184
+ // with the real message instead of an opaque retryable 500.
185
+ if (!res.ok && body?.errors?.length) {
186
+ const msg = body.errors.map((e) => e.message).join('; ');
187
+ throw new CliError(EXIT.API, `The API rejected the request (HTTP ${res.status}): ${msg}`,
188
+ { reason: 'graphql_error', retryable: false, details: body.errors });
189
+ }
183
190
  return body;
184
191
  }
185
192
 
package/src/queries.js CHANGED
@@ -230,6 +230,25 @@ export const VOUCHERS = `query customerVouchersCli {
230
230
  }
231
231
  }`;
232
232
 
233
+ export const NEXT_SUGGESTION_APPLIED_VOUCHER = `query nextSuggestionAppliedVoucher {
234
+ nextSuggestion { id appliedVoucher { code appliedDiscount } }
235
+ }`;
236
+
237
+ export const ASSIGN_NEXT_SUGGESTION_VOUCHER = `mutation assignNextSuggestionVoucher($voucherCode: String, $skipVoucher: Boolean!, $suggestionId: ModelId!) {
238
+ assignNextSuggestionVoucher(voucherCode: $voucherCode, skipVoucher: $skipVoucher, suggestionId: $suggestionId) {
239
+ appliedVoucher { code appliedDiscount }
240
+ skipVoucher
241
+ }
242
+ }`;
243
+
244
+ export const GIFT_CARDS_CONFIG = `query giftCardsConfiguration {
245
+ giftCardsConfiguration { minAmount maxAmount }
246
+ }`;
247
+
248
+ export const REDEEM_GIFT_CARD = `mutation redeemGiftCard($code: String!) {
249
+ redeemGiftCard(code: $code) { code amount }
250
+ }`;
251
+
233
252
  export const WALLET = `query walletBalance { walletBalance }`;
234
253
 
235
254
  export const LOGOUT = `query registerLogout { registerLogout }`;