@stewardhq/cli 0.9.0 → 0.11.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +19 -32
- package/dist/bin.js +734 -77
- package/package.json +5 -5
package/dist/bin.js
CHANGED
|
@@ -2,13 +2,13 @@
|
|
|
2
2
|
import { userInfo } from "node:os";
|
|
3
3
|
import { createInterface } from "node:readline/promises";
|
|
4
4
|
import { setTimeout } from "node:timers/promises";
|
|
5
|
-
import { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CreditAdjustmentInputSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf } from "@stewardhq/sdk";
|
|
5
|
+
import { ACCOUNT_INCLUDES, AccountMetadataPatchInputSchema, ApiKeyCreateInputSchema, BankTransferRecordInputSchema, CatalogSyncInputSchema, CodeSchema, CreditAdjustmentInputSchema, DateTimeSchema, DunningPolicySchema, EventsIngestInputSchema, FxRateSchema, GRANT_LIST_DEFAULT_LIMIT, GRANT_LIST_MAX_LIMIT, GrantListSubscriptionFilterSchema, INVOICE_LINE_TEXTS, IdSchema, InvoiceIssueInputSchema, InvoicePaymentStatusSchema, InvoiceStatusSchema, METER_CHARGE_MODES, MeterCreditPropertiesSchema, ProductSettingsPatchSchema, RepriceInputSchema, SALES_REPORT_MAX_MONTHS, StewardApiError, StewardConfigError, StewardError, StewardNetworkError, TAX_PROVIDERS, TAX_THRESHOLD_PERIODS, TAX_THRESHOLD_SCOPES, TaxThresholdInputSchema, WebhookEndpointCreateInputSchema, WebhookEndpointRotateInputSchema, createSteward, generateApiKeyToken, generateWebhookSecret, plainDecimalOf, taxIdTypeOf } from "@stewardhq/sdk";
|
|
6
6
|
import { parseArgs } from "node:util";
|
|
7
7
|
import { basename, dirname, extname, join, relative, resolve } from "node:path";
|
|
8
8
|
import { link, lstat, readFile, rename, unlink, writeFile } from "node:fs/promises";
|
|
9
9
|
import { randomUUID } from "node:crypto";
|
|
10
10
|
import { pathToFileURL } from "node:url";
|
|
11
|
-
|
|
11
|
+
// src/io.ts
|
|
12
12
|
const SECRET_PATTERN = /\b(whsec_|stw_)[A-Za-z0-9_\-+/=]+/g;
|
|
13
13
|
/** Masks secret-shaped values (`whsec_***`). */
|
|
14
14
|
function redactSecrets(text) {
|
|
@@ -41,8 +41,7 @@ function errnoCode(error) {
|
|
|
41
41
|
const code = typeof error === "object" && error !== null ? error.code : void 0;
|
|
42
42
|
return typeof code === "string" ? code : void 0;
|
|
43
43
|
}
|
|
44
|
-
|
|
45
|
-
//#region src/args.ts
|
|
44
|
+
// src/args.ts
|
|
46
45
|
const HELP_OPTION = { help: {
|
|
47
46
|
type: "boolean",
|
|
48
47
|
short: "h"
|
|
@@ -105,8 +104,7 @@ function parseBoolean(value, flag) {
|
|
|
105
104
|
].includes(text)) return false;
|
|
106
105
|
throw new UsageError(`${flag}: must be true or false`);
|
|
107
106
|
}
|
|
108
|
-
|
|
109
|
-
//#region src/catalog-diff.ts
|
|
107
|
+
// src/catalog-diff.ts
|
|
110
108
|
/** A catalog that defines benefits needs a steward with the `benefits` capability (M27). */
|
|
111
109
|
function definesBenefits(input) {
|
|
112
110
|
return Object.keys(input.benefits ?? {}).length > 0;
|
|
@@ -138,7 +136,7 @@ function formatMinor(amountMinor, currency) {
|
|
|
138
136
|
return `${amountMinor} ${currency} (minor units)`;
|
|
139
137
|
}
|
|
140
138
|
}
|
|
141
|
-
const percent = (bps) => `${bps / 100}%`;
|
|
139
|
+
const percent$1 = (bps) => `${bps / 100}%`;
|
|
142
140
|
/** Units as exact text with grouping (`2,000,000`, `0.25`). */
|
|
143
141
|
const unitsText = (value) => new Intl.NumberFormat("en", { maximumFractionDigits: 6 }).format(plainDecimalOf(value));
|
|
144
142
|
const meteredKey = (p) => `${p.planCode}/${p.meter}/${p.currency}`;
|
|
@@ -286,7 +284,7 @@ function diffCatalog(current, file) {
|
|
|
286
284
|
function describePriceChange({ label, currency, from, to }) {
|
|
287
285
|
const parts = [];
|
|
288
286
|
if (from.amountMinor !== to.amountMinor) parts.push(`${formatMinor(from.amountMinor, currency)} → ${formatMinor(to.amountMinor, currency)}`);
|
|
289
|
-
if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
|
|
287
|
+
if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent$1(from.taxRateBps)} → ${percent$1(to.taxRateBps)}`);
|
|
290
288
|
if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
|
|
291
289
|
return `${from.amountMinor === to.amountMinor ? `${label} ${formatMinor(to.amountMinor, currency)}` : label}: ${parts.join(", ")}`;
|
|
292
290
|
}
|
|
@@ -305,7 +303,7 @@ function describeMeteredPriceChange({ label, currency, from, to }) {
|
|
|
305
303
|
const cap = (minor) => minor === null ? "none" : formatMinor(minor, currency);
|
|
306
304
|
parts.push(`cap ${cap(from.capMinor)} → ${cap(to.capMinor)}`);
|
|
307
305
|
}
|
|
308
|
-
if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent(from.taxRateBps)} → ${percent(to.taxRateBps)}`);
|
|
306
|
+
if (from.taxRateBps !== to.taxRateBps) parts.push(`tax rate ${percent$1(from.taxRateBps)} → ${percent$1(to.taxRateBps)}`);
|
|
309
307
|
if (from.taxInclusive !== to.taxInclusive) parts.push(`tax ${from.taxInclusive ? "inclusive" : "exclusive"} → ${to.taxInclusive ? "inclusive" : "exclusive"}`);
|
|
310
308
|
return `${label}: ${parts.join(", ")}`;
|
|
311
309
|
}
|
|
@@ -359,8 +357,7 @@ function describeDiff(diff) {
|
|
|
359
357
|
function priceChangeCount(diff) {
|
|
360
358
|
return diff.prices.changed.length + diff.meteredPrices.changed.length;
|
|
361
359
|
}
|
|
362
|
-
|
|
363
|
-
//#region src/dotenv.ts
|
|
360
|
+
// src/dotenv.ts
|
|
364
361
|
const LINE = /^(\s*)(export\s+)?([A-Za-z_][A-Za-z0-9_.-]*)\s*=(.*)$/;
|
|
365
362
|
function unquote(rest) {
|
|
366
363
|
const value = rest.trim();
|
|
@@ -391,8 +388,7 @@ async function readDotenvFile(path) {
|
|
|
391
388
|
throw error;
|
|
392
389
|
}
|
|
393
390
|
}
|
|
394
|
-
|
|
395
|
-
//#region src/env.ts
|
|
391
|
+
// src/env.ts
|
|
396
392
|
const ENV_LOCAL = ".env.local";
|
|
397
393
|
/** If even one of these is in the process environment, `.env.local` is not read. */
|
|
398
394
|
const CONNECTION_VARIABLES = [
|
|
@@ -526,8 +522,7 @@ function describeStewardError(error, target) {
|
|
|
526
522
|
}
|
|
527
523
|
return `steward response does not match the contract${where}: ${error.code} (HTTP ${error.httpStatus}) — the CLI and steward versions may be incompatible${request}`;
|
|
528
524
|
}
|
|
529
|
-
|
|
530
|
-
//#region src/commands/accounts.ts
|
|
525
|
+
// src/commands/accounts.ts
|
|
531
526
|
const ACCOUNTS_USAGE = `Usage:
|
|
532
527
|
steward accounts get <ref> [--include <a,b>] [--json]
|
|
533
528
|
steward accounts metadata set <ref> <key>=<value>… [--reason <text>] [--json]
|
|
@@ -703,8 +698,7 @@ async function accountsCommand(ctx, out, args) {
|
|
|
703
698
|
if (sub === "metadata") return metadataCommand(ctx, out, rest);
|
|
704
699
|
throw new UsageError(`unknown subcommand: accounts ${sub} (see: steward accounts --help)`);
|
|
705
700
|
}
|
|
706
|
-
|
|
707
|
-
//#region src/confirm.ts
|
|
701
|
+
// src/confirm.ts
|
|
708
702
|
/**
|
|
709
703
|
* Asks before a change that cannot be taken back; `yes` (`--yes`) skips the question. Without a
|
|
710
704
|
* terminal (CI, pipes) the command needs `--yes`: `notConfirmed` says what was not done.
|
|
@@ -715,8 +709,7 @@ async function confirm(ctx, question, options) {
|
|
|
715
709
|
if (answer === null) throw new CliError(`confirmation needed: run again with --yes (${options.notConfirmed})`);
|
|
716
710
|
return /^y(es)?$/i.test(answer.trim());
|
|
717
711
|
}
|
|
718
|
-
|
|
719
|
-
//#region src/secret-file.ts
|
|
712
|
+
// src/secret-file.ts
|
|
720
713
|
async function withSecretFile(cwd, out, secret, options, action) {
|
|
721
714
|
const target = resolve(cwd, out);
|
|
722
715
|
try {
|
|
@@ -763,8 +756,7 @@ async function withSecretFile(cwd, out, secret, options, action) {
|
|
|
763
756
|
};
|
|
764
757
|
}
|
|
765
758
|
}
|
|
766
|
-
|
|
767
|
-
//#region src/commands/endpoints.ts
|
|
759
|
+
// src/commands/endpoints.ts
|
|
768
760
|
const ENDPOINTS_USAGE = `Usage:
|
|
769
761
|
steward endpoints list [--json]
|
|
770
762
|
steward endpoints add --url <url> --out <file> [--event-types <a,b>] [--description <text>] [--force]
|
|
@@ -806,7 +798,7 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
806
798
|
...HELP_OPTION,
|
|
807
799
|
json: { type: "boolean" }
|
|
808
800
|
}, "endpoints");
|
|
809
|
-
if (values.help) return help$
|
|
801
|
+
if (values.help) return help$5(out);
|
|
810
802
|
expectPositionals(positionals, 0, 0, "endpoints");
|
|
811
803
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
812
804
|
out.err(connectionLine(target));
|
|
@@ -841,7 +833,7 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
841
833
|
description: { type: "string" },
|
|
842
834
|
force: { type: "boolean" }
|
|
843
835
|
}, ENDPOINTS_USAGE);
|
|
844
|
-
if (values.help) return help$
|
|
836
|
+
if (values.help) return help$5(out);
|
|
845
837
|
expectPositionals(positionals, 0, 0, "endpoints");
|
|
846
838
|
const url = requireOption(values.url, "--url", "endpoints");
|
|
847
839
|
const file = requireOption(values.out, "--out", "endpoints");
|
|
@@ -872,7 +864,7 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
872
864
|
out: { type: "string" },
|
|
873
865
|
force: { type: "boolean" }
|
|
874
866
|
}, "endpoints");
|
|
875
|
-
if (values.help) return help$
|
|
867
|
+
if (values.help) return help$5(out);
|
|
876
868
|
expectPositionals(positionals, 1, 1, "endpoints");
|
|
877
869
|
const id = positionals[0];
|
|
878
870
|
const file = requireOption(values.out, "--out", "endpoints");
|
|
@@ -891,7 +883,7 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
891
883
|
}
|
|
892
884
|
if (sub === "deactivate") {
|
|
893
885
|
const { values, positionals } = parse(rest, { ...HELP_OPTION }, "endpoints");
|
|
894
|
-
if (values.help) return help$
|
|
886
|
+
if (values.help) return help$5(out);
|
|
895
887
|
expectPositionals(positionals, 1, 1, "endpoints");
|
|
896
888
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
897
889
|
out.err(connectionLine(target));
|
|
@@ -901,7 +893,7 @@ async function endpointsCommand(ctx, out, args) {
|
|
|
901
893
|
}
|
|
902
894
|
throw new UsageError(`unknown subcommand: endpoints ${sub} (details: steward endpoints --help)`);
|
|
903
895
|
}
|
|
904
|
-
function help$
|
|
896
|
+
function help$5(out) {
|
|
905
897
|
out.out(ENDPOINTS_USAGE);
|
|
906
898
|
return 0;
|
|
907
899
|
}
|
|
@@ -911,15 +903,14 @@ function secretNotice(out, path, fallback, next) {
|
|
|
911
903
|
out.out(` secret ${path} (0600; not written to the terminal)`);
|
|
912
904
|
out.err(next);
|
|
913
905
|
}
|
|
914
|
-
|
|
915
|
-
//#region src/commands/bank-transfers.ts
|
|
906
|
+
// src/commands/bank-transfers.ts
|
|
916
907
|
const BANK_TRANSFERS_USAGE = `Usage:
|
|
917
908
|
steward bank-transfers list [--status pending|expired] [--rate <rate> [--currency <CUR>]]
|
|
918
909
|
[--json]
|
|
919
910
|
steward bank-transfers record <code> --amount <minor> --currency <CUR> --received-at <iso>
|
|
920
911
|
--bank-ref <ref> [--rate <rate>]
|
|
921
912
|
[--checkout <id> [--accept-expired] | --invoice <id>]
|
|
922
|
-
[--yes] [--json]
|
|
913
|
+
[--override-billing-currency] [--yes] [--json]
|
|
923
914
|
steward bank-transfers fx-report [--from <iso>] [--to <iso>] [--json | --csv]
|
|
924
915
|
|
|
925
916
|
Bank transfer (havale/EFT) reconciliation (/v1/admin/bank-transfers).
|
|
@@ -929,7 +920,9 @@ transfer and unpaid invoices of accounts with an order code, by deadline; expire
|
|
|
929
920
|
that expired in the last 30 days. --rate previews a transfer in another currency: next to each
|
|
930
921
|
item the product lets be paid in another currency (settings.billing.bankTransfer.settleIn) it
|
|
931
922
|
shows the amount expected at that rate (--currency names it when an item accepts several). It
|
|
932
|
-
writes nothing.
|
|
923
|
+
writes nothing. INVOICE NO is the number an invoice was issued with in the external system
|
|
924
|
+
(- : not issued yet, or a checkout, whose invoice is written when the transfer is recorded;
|
|
925
|
+
see steward invoices --help).
|
|
933
926
|
|
|
934
927
|
record: a transfer seen on the bank account. <code> is the order code from the transfer
|
|
935
928
|
description (case and dashes are forgiven). Only a checkout or unpaid invoice waiting for
|
|
@@ -947,13 +940,17 @@ within the product's tolerance (fxToleranceBps, default 0.5%) of its amount at t
|
|
|
947
940
|
is settled in its own currency. --rate is required for such a transfer and refused for one in
|
|
948
941
|
the item's currency. Steward never looks a rate up.
|
|
949
942
|
|
|
943
|
+
record --override-billing-currency: settle a checkout that is not in the account's billing
|
|
944
|
+
currency (another payment fixed it after the checkout opened; refused with currency_mismatch
|
|
945
|
+
otherwise). Not needed for an invoice, nor for a checkout the product opened with the override.
|
|
946
|
+
|
|
950
947
|
fx-report: the payments received in another currency (invoice number and date, amount settled,
|
|
951
948
|
amount received, the rate entered, received date), latest first; --from (inclusive) and --to
|
|
952
949
|
(exclusive) are ISO-8601 with an offset, by received date. The accountant's input for
|
|
953
950
|
exchange-difference invoices, which steward does not issue.
|
|
954
951
|
|
|
955
952
|
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
956
|
-
const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
953
|
+
const WITH_OFFSET$1 = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
957
954
|
async function bankTransfersCommand(ctx, out, args) {
|
|
958
955
|
const [sub, ...rest] = args;
|
|
959
956
|
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
@@ -968,7 +965,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
968
965
|
currency: { type: "string" },
|
|
969
966
|
json: { type: "boolean" }
|
|
970
967
|
}, "bank-transfers");
|
|
971
|
-
if (values.help) return help$
|
|
968
|
+
if (values.help) return help$4(out);
|
|
972
969
|
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
973
970
|
const status = values.status ?? "pending";
|
|
974
971
|
if (status !== "pending" && status !== "expired") throw new UsageError("--status: pending or expired");
|
|
@@ -992,6 +989,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
992
989
|
...rate !== void 0 ? [`EXPECTED @ ${rate}`] : [],
|
|
993
990
|
"DEADLINE",
|
|
994
991
|
"KIND",
|
|
992
|
+
"INVOICE NO",
|
|
995
993
|
"PLAN",
|
|
996
994
|
"ACCOUNT",
|
|
997
995
|
"ID"
|
|
@@ -1002,6 +1000,7 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
1002
1000
|
...rate !== void 0 ? [i.expectedMinor !== void 0 && i.expectedCurrency !== void 0 ? formatMinor(i.expectedMinor, i.expectedCurrency) : "-"] : [],
|
|
1003
1001
|
i.deadline ?? "-",
|
|
1004
1002
|
i.kind,
|
|
1003
|
+
i.invoiceNumber ?? "-",
|
|
1005
1004
|
i.planCode ?? "-",
|
|
1006
1005
|
i.accountRef,
|
|
1007
1006
|
i.id
|
|
@@ -1021,16 +1020,17 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
1021
1020
|
checkout: { type: "string" },
|
|
1022
1021
|
invoice: { type: "string" },
|
|
1023
1022
|
"accept-expired": { type: "boolean" },
|
|
1023
|
+
"override-billing-currency": { type: "boolean" },
|
|
1024
1024
|
yes: {
|
|
1025
1025
|
type: "boolean",
|
|
1026
1026
|
short: "y"
|
|
1027
1027
|
},
|
|
1028
1028
|
json: { type: "boolean" }
|
|
1029
1029
|
}, "bank-transfers");
|
|
1030
|
-
if (values.help) return help$
|
|
1030
|
+
if (values.help) return help$4(out);
|
|
1031
1031
|
expectPositionals(positionals, 1, 1, "bank-transfers");
|
|
1032
1032
|
const receivedAt = requireOption(values["received-at"], "--received-at", "bank-transfers");
|
|
1033
|
-
if (!WITH_OFFSET.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
|
|
1033
|
+
if (!WITH_OFFSET$1.test(receivedAt)) throw new UsageError("--received-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
|
|
1034
1034
|
const input = {
|
|
1035
1035
|
code: positionals[0],
|
|
1036
1036
|
amountMinor: parseNonNegativeInt(requireOption(values.amount, "--amount", "bank-transfers"), "--amount"),
|
|
@@ -1040,7 +1040,8 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
1040
1040
|
...values.rate !== void 0 ? { rate: parseRate(values.rate) } : {},
|
|
1041
1041
|
...values.checkout !== void 0 ? { checkoutSessionId: values.checkout } : {},
|
|
1042
1042
|
...values.invoice !== void 0 ? { invoiceId: values.invoice } : {},
|
|
1043
|
-
...values["accept-expired"] ? { acceptExpired: true } : {}
|
|
1043
|
+
...values["accept-expired"] ? { acceptExpired: true } : {},
|
|
1044
|
+
...values["override-billing-currency"] ? { overrideBillingCurrency: true } : {}
|
|
1044
1045
|
};
|
|
1045
1046
|
const parsed = BankTransferRecordInputSchema.safeParse(input);
|
|
1046
1047
|
if (!parsed.success) throw new UsageError(`invalid transfer (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
@@ -1070,11 +1071,11 @@ async function bankTransfersCommand(ctx, out, args) {
|
|
|
1070
1071
|
json: { type: "boolean" },
|
|
1071
1072
|
csv: { type: "boolean" }
|
|
1072
1073
|
}, "bank-transfers");
|
|
1073
|
-
if (values.help) return help$
|
|
1074
|
+
if (values.help) return help$4(out);
|
|
1074
1075
|
expectPositionals(positionals, 0, 0, "bank-transfers");
|
|
1075
1076
|
if (values.json && values.csv) throw new UsageError("--json or --csv, not both");
|
|
1076
|
-
if (values.from !== void 0 && !WITH_OFFSET.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
|
|
1077
|
-
if (values.to !== void 0 && !WITH_OFFSET.test(values.to)) throw new UsageError("--to: ISO-8601 with an offset (2026-10-01T00:00:00+03:00)");
|
|
1077
|
+
if (values.from !== void 0 && !WITH_OFFSET$1.test(values.from)) throw new UsageError("--from: ISO-8601 with an offset (2026-09-01T00:00:00+03:00)");
|
|
1078
|
+
if (values.to !== void 0 && !WITH_OFFSET$1.test(values.to)) throw new UsageError("--to: ISO-8601 with an offset (2026-10-01T00:00:00+03:00)");
|
|
1078
1079
|
const range = {
|
|
1079
1080
|
...values.from !== void 0 ? { from: values.from } : {},
|
|
1080
1081
|
...values.to !== void 0 ? { to: values.to } : {}
|
|
@@ -1135,12 +1136,11 @@ function csvField(value) {
|
|
|
1135
1136
|
const text = typeof value === "string" && /^[=+\-@]/.test(value) ? `'${value}` : String(value);
|
|
1136
1137
|
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, "\"\"")}"` : text;
|
|
1137
1138
|
}
|
|
1138
|
-
function help$
|
|
1139
|
+
function help$4(out) {
|
|
1139
1140
|
out.out(BANK_TRANSFERS_USAGE);
|
|
1140
1141
|
return 0;
|
|
1141
1142
|
}
|
|
1142
|
-
|
|
1143
|
-
//#region src/catalog-file.ts
|
|
1143
|
+
// src/catalog-file.ts
|
|
1144
1144
|
const MODULE_EXTENSIONS = /* @__PURE__ */ new Set([
|
|
1145
1145
|
".js",
|
|
1146
1146
|
".mjs",
|
|
@@ -1200,8 +1200,7 @@ async function loadCatalogFile(ctx, file) {
|
|
|
1200
1200
|
if (!parsed.success) throw new CliError(`${file}: invalid catalog (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
1201
1201
|
return input;
|
|
1202
1202
|
}
|
|
1203
|
-
|
|
1204
|
-
//#region src/commands/catalog.ts
|
|
1203
|
+
// src/commands/catalog.ts
|
|
1205
1204
|
const CATALOG_USAGE = `Usage: steward catalog push <file> [--yes]
|
|
1206
1205
|
|
|
1207
1206
|
Syncs the catalog definition to steward (PUT /v1/admin/catalog), then prints the version
|
|
@@ -1336,8 +1335,7 @@ async function catalogCommand(ctx, out, args) {
|
|
|
1336
1335
|
for (const line of lines) out.out(line);
|
|
1337
1336
|
return providerErrors > 0 ? 1 : 0;
|
|
1338
1337
|
}
|
|
1339
|
-
|
|
1340
|
-
//#region src/commands/meters.ts
|
|
1338
|
+
// src/commands/meters.ts
|
|
1341
1339
|
const METERS_USAGE = `Usage:
|
|
1342
1340
|
steward meters get <ref> [--periods <n>] [--json]
|
|
1343
1341
|
steward meters recompute <ref> [--meter <code>] [--json]
|
|
@@ -1460,8 +1458,7 @@ async function metersCommand(ctx, out, args) {
|
|
|
1460
1458
|
else for (const line of formatMeters(meters, periods)) out.out(line);
|
|
1461
1459
|
return 0;
|
|
1462
1460
|
}
|
|
1463
|
-
|
|
1464
|
-
//#region src/commands/credits.ts
|
|
1461
|
+
// src/commands/credits.ts
|
|
1465
1462
|
const CREDITS_USAGE = `Usage: steward credits adjust <ref> <meter> --units=<n> --reason <text> [--json]
|
|
1466
1463
|
|
|
1467
1464
|
One credit ledger entry for the meter's current usage period of account <ref>
|
|
@@ -1514,8 +1511,7 @@ async function creditsCommand(ctx, out, args) {
|
|
|
1514
1511
|
if (read !== void 0) out.out(` balance ${formatUnitsText(read.balance)} · standing ${read.standing}`);
|
|
1515
1512
|
return 0;
|
|
1516
1513
|
}
|
|
1517
|
-
|
|
1518
|
-
//#region src/commands/doctor.ts
|
|
1514
|
+
// src/commands/doctor.ts
|
|
1519
1515
|
const DOCTOR_USAGE = `Usage: steward doctor [--json]
|
|
1520
1516
|
|
|
1521
1517
|
The GET /v1/doctor report. Sections in order: status, catalog, provider, settings,
|
|
@@ -1659,11 +1655,18 @@ function formatDoctorReport(report, cliWarnings, metering = null) {
|
|
|
1659
1655
|
lines.push(`catalog synced ${yesNo(catalog.synced)}${catalog.version !== null ? ` · version ${catalog.version}` : ""} · ${plural(catalog.plans, "plan")} · ${plural(catalog.sellablePrices, "sellable price")} · ${catalog.unsellablePrices.length} unsellable`);
|
|
1660
1656
|
for (const price of catalog.unsellablePrices) lines.push(` ✗ ${price.planCode} ${price.interval}×${price.intervalCount} ${price.currency}: ${price.reason}`);
|
|
1661
1657
|
const providerState = !provider.configured ? "not configured ✗" : provider.healthy === false ? "unreachable !" : "configured ✓";
|
|
1658
|
+
const webhook = provider.webhook ? ` · webhook ${provider.webhook.configured ? `configured ✓ (last event ${provider.webhook.lastEventAt ?? "never"})` : "not configured ✗"}${provider.webhook.openDisputes > 0 ? ` · ${provider.webhook.openDisputes} open dispute(s) !` : ""}` : "";
|
|
1659
|
+
const renewal = provider.automaticRenewal ? ` · automatic renewal active ✓ (${provider.automaticRenewal.subscriptionsWithCard} with a saved card, ${provider.automaticRenewal.subscriptionsWithoutCard} without; renewal notice ${provider.automaticRenewal.renewalNotice ? `${provider.automaticRenewal.renewalNotice.daysBefore} days before, ${provider.automaticRenewal.renewalNotice.intervals.join("/")}` : "off"})` : provider.configured ? " · automatic renewal off (invoice e-mail and pay page)" : "";
|
|
1662
1660
|
const providerError = provider.lastError ? ` · last error ${provider.lastError.code} (${provider.lastError.operation}, ${provider.lastError.at})` : "";
|
|
1663
|
-
lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${providerError}`);
|
|
1661
|
+
lines.push(`provider ${provider.id}${provider.environment !== null ? ` · ${provider.environment}` : ""} · ${providerState}${webhook}${renewal}${providerError}`);
|
|
1664
1662
|
lines.push(`settings appUrl ${settings.appUrl ?? "none"} · return origins: ${settings.returnOrigins.length > 0 ? settings.returnOrigins.join(", ") : "none"}`);
|
|
1665
1663
|
const missing = [...hosted.branding.missing.map((field) => `branding.${field}`), ...hosted.legalLinks.missing];
|
|
1666
1664
|
lines.push(`hosted ${hosted.ready ? "ready ✓" : `not ready ✗${missing.length > 0 ? ` (missing: ${missing.join(", ")})` : ""}`}`);
|
|
1665
|
+
if (report.legal) {
|
|
1666
|
+
const legal = report.legal;
|
|
1667
|
+
const mark = (set) => set ? "✓" : "✗";
|
|
1668
|
+
lines.push(`legal seller ${mark(legal.seller)} · withdrawal waiver ${legal.withdrawalWaiver ? `${legal.withdrawalWaiver.version} ✓` : "✗"}` + (legal.cardSaved ? ` · card-on-file consent ${legal.cardOnFile ? `${legal.cardOnFile.version} ✓` : "✗"}` : "") + (legal.pendingErasures > 0 ? ` · ${legal.pendingErasures} provider erasure(s) pending !` : ""));
|
|
1669
|
+
}
|
|
1667
1670
|
if (report.endpoints.length === 0) lines.push("endpoints none");
|
|
1668
1671
|
else {
|
|
1669
1672
|
lines.push("endpoints");
|
|
@@ -1728,8 +1731,7 @@ async function doctorCommand(ctx, out, args) {
|
|
|
1728
1731
|
else for (const line of formatDoctorReport(report, cliWarnings, metering)) out.out(line);
|
|
1729
1732
|
return failed ? 1 : 0;
|
|
1730
1733
|
}
|
|
1731
|
-
|
|
1732
|
-
//#region src/commands/dunning.ts
|
|
1734
|
+
// src/commands/dunning.ts
|
|
1733
1735
|
const DUNNING_USAGE = `Usage:
|
|
1734
1736
|
steward dunning get [--json]
|
|
1735
1737
|
steward dunning set <policy.json> [--yes]
|
|
@@ -1755,7 +1757,7 @@ async function dunningCommand(ctx, out, args) {
|
|
|
1755
1757
|
...HELP_OPTION,
|
|
1756
1758
|
json: { type: "boolean" }
|
|
1757
1759
|
}, "dunning");
|
|
1758
|
-
if (values.help) return help$
|
|
1760
|
+
if (values.help) return help$3(out);
|
|
1759
1761
|
expectPositionals(positionals, 0, 0, "dunning");
|
|
1760
1762
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1761
1763
|
out.err(connectionLine(target));
|
|
@@ -1772,7 +1774,7 @@ async function dunningCommand(ctx, out, args) {
|
|
|
1772
1774
|
short: "y"
|
|
1773
1775
|
}
|
|
1774
1776
|
}, "dunning");
|
|
1775
|
-
if (values.help) return help$
|
|
1777
|
+
if (values.help) return help$3(out);
|
|
1776
1778
|
expectPositionals(positionals, 1, 1, "dunning");
|
|
1777
1779
|
const file = positionals[0];
|
|
1778
1780
|
let json;
|
|
@@ -1805,12 +1807,11 @@ async function dunningCommand(ctx, out, args) {
|
|
|
1805
1807
|
}
|
|
1806
1808
|
throw new UsageError(`unknown subcommand: dunning ${sub} (see: steward dunning --help)`);
|
|
1807
1809
|
}
|
|
1808
|
-
function help$
|
|
1810
|
+
function help$3(out) {
|
|
1809
1811
|
out.out(DUNNING_USAGE);
|
|
1810
1812
|
return 0;
|
|
1811
1813
|
}
|
|
1812
|
-
|
|
1813
|
-
//#region src/commands/events.ts
|
|
1814
|
+
// src/commands/events.ts
|
|
1814
1815
|
const EVENTS_USAGE = `Usage:
|
|
1815
1816
|
steward events send <ref> <name> [--meta key=value]… [--external-id <id>]
|
|
1816
1817
|
[--timestamp <iso>] [--json]
|
|
@@ -1936,8 +1937,334 @@ async function redeliverCommand(ctx, out, args) {
|
|
|
1936
1937
|
}
|
|
1937
1938
|
return 0;
|
|
1938
1939
|
}
|
|
1939
|
-
|
|
1940
|
-
|
|
1940
|
+
// src/commands/grants.ts
|
|
1941
|
+
const GRANTS_USAGE = `Usage:
|
|
1942
|
+
steward grants list [--plan <code>] [--subscription none|live|any] [--limit <n>]
|
|
1943
|
+
[--after <grant id>] [--json]
|
|
1944
|
+
|
|
1945
|
+
The product's active grants (not revoked, started, not ended), one line per grant, with the
|
|
1946
|
+
account and its live subscriptions (GET /v1/admin/grants).
|
|
1947
|
+
|
|
1948
|
+
--plan: only the grants of that plan (a code the product never had is refused). Without it,
|
|
1949
|
+
grants of named benefits or overrides only are listed too (plan -).
|
|
1950
|
+
--subscription: none = accounts with no live subscription (active, past_due, suspended), e.g.
|
|
1951
|
+
granted a plan but paying for nothing; live = accounts with one; any (default) = both.
|
|
1952
|
+
--limit: 1–${GRANT_LIST_MAX_LIMIT}, default ${GRANT_LIST_DEFAULT_LIMIT}; a cut list says so on stderr with the --after
|
|
1953
|
+
value of the next page.
|
|
1954
|
+
|
|
1955
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
1956
|
+
async function grantsCommand(ctx, out, args) {
|
|
1957
|
+
const [sub, ...rest] = args;
|
|
1958
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
1959
|
+
out.out(GRANTS_USAGE);
|
|
1960
|
+
return sub === void 0 ? 2 : 0;
|
|
1961
|
+
}
|
|
1962
|
+
if (sub === "list") {
|
|
1963
|
+
const { values, positionals } = parse(rest, {
|
|
1964
|
+
...HELP_OPTION,
|
|
1965
|
+
plan: { type: "string" },
|
|
1966
|
+
subscription: { type: "string" },
|
|
1967
|
+
limit: { type: "string" },
|
|
1968
|
+
after: { type: "string" },
|
|
1969
|
+
json: { type: "boolean" }
|
|
1970
|
+
}, "grants");
|
|
1971
|
+
if (values.help) {
|
|
1972
|
+
out.out(GRANTS_USAGE);
|
|
1973
|
+
return 0;
|
|
1974
|
+
}
|
|
1975
|
+
expectPositionals(positionals, 0, 0, "grants");
|
|
1976
|
+
if (values.plan !== void 0 && !CodeSchema.safeParse(values.plan).success) throw new UsageError("--plan: a plan code");
|
|
1977
|
+
const subscription = GrantListSubscriptionFilterSchema.optional().safeParse(values.subscription);
|
|
1978
|
+
if (!subscription.success) throw new UsageError("--subscription: none, live or any");
|
|
1979
|
+
if (values.after !== void 0 && !IdSchema.safeParse(values.after).success) throw new UsageError("--after: a grant id");
|
|
1980
|
+
const limit = values.limit !== void 0 ? parsePositiveInt(values.limit, "--limit", { max: GRANT_LIST_MAX_LIMIT }) : void 0;
|
|
1981
|
+
const filter = {
|
|
1982
|
+
...values.plan !== void 0 ? { plan: values.plan } : {},
|
|
1983
|
+
...subscription.data !== void 0 ? { subscription: subscription.data } : {},
|
|
1984
|
+
...limit !== void 0 ? { limit } : {},
|
|
1985
|
+
...values.after !== void 0 ? { after: values.after } : {}
|
|
1986
|
+
};
|
|
1987
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1988
|
+
out.err(connectionLine(target));
|
|
1989
|
+
const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.grants.list(filter));
|
|
1990
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
1991
|
+
else if (items.length === 0) out.out("no active grants");
|
|
1992
|
+
else {
|
|
1993
|
+
const rows = [[
|
|
1994
|
+
"ACCOUNT",
|
|
1995
|
+
"NAME",
|
|
1996
|
+
"PLAN",
|
|
1997
|
+
"ENDS",
|
|
1998
|
+
"SUBSCRIPTIONS",
|
|
1999
|
+
"GRANT",
|
|
2000
|
+
"REASON"
|
|
2001
|
+
]];
|
|
2002
|
+
for (const g of items) rows.push([
|
|
2003
|
+
g.accountRef,
|
|
2004
|
+
g.accountDisplayName || "-",
|
|
2005
|
+
g.planCode ?? "-",
|
|
2006
|
+
g.endsAt ?? "-",
|
|
2007
|
+
g.liveSubscriptions.map((s) => `${s.planCode}/${s.interval} ${s.status}`).join(", ") || "-",
|
|
2008
|
+
g.grantId,
|
|
2009
|
+
g.reason
|
|
2010
|
+
]);
|
|
2011
|
+
for (const line of table(rows)) out.out(line);
|
|
2012
|
+
}
|
|
2013
|
+
const last = items.at(-1);
|
|
2014
|
+
if (hasMore && last !== void 0) out.err(`more grants than the ${limit ?? GRANT_LIST_DEFAULT_LIMIT} listed; next page: --after ${last.grantId}`);
|
|
2015
|
+
return 0;
|
|
2016
|
+
}
|
|
2017
|
+
throw new UsageError(`unknown subcommand: grants ${sub} (see: steward grants --help)`);
|
|
2018
|
+
}
|
|
2019
|
+
// src/commands/invoices.ts
|
|
2020
|
+
const INVOICES_USAGE = `Usage:
|
|
2021
|
+
steward invoices list [--status draft|issued|void|all] [--payment-status <status>]
|
|
2022
|
+
[--from <iso>] [--to <iso>] [--limit <n>] [--json | --csv]
|
|
2023
|
+
steward invoices issue <id> --number <number> [--external-ref <ref>] [--issued-at <iso>]
|
|
2024
|
+
[--document <file.pdf>] [--yes] [--json]
|
|
2025
|
+
|
|
2026
|
+
Tracking which invoices have been cut in the external system (e-Arşiv, the accountant's software).
|
|
2027
|
+
|
|
2028
|
+
list: the product's invoices, oldest first (GET /v1/admin/invoices). draft (default): the ones
|
|
2029
|
+
not issued yet, i.e. with no number of the external system; issued: the ones that have it; all:
|
|
2030
|
+
every status. --payment-status narrows it (unpaid, paid, …). --from (inclusive) and --to
|
|
2031
|
+
(exclusive), ISO-8601 with an offset, keep the invoices written in that window. --limit: 1–500,
|
|
2032
|
+
default 100; a cut list says so on stderr.
|
|
2033
|
+
|
|
2034
|
+
--csv is the export for an accounting system that issues the invoices (one row per invoice, a
|
|
2035
|
+
header row first): the invoice, its amounts in minor units, the tax decision (treatment, reason,
|
|
2036
|
+
tax country), the period, the payment (date, method, reference), the buyer copy (kind, names,
|
|
2037
|
+
contact, address with postal code, region and country, tax ID with its type) and the lines as a
|
|
2038
|
+
JSON array. Columns are only ever added at the end. --json prints the items as the API returns them.
|
|
2039
|
+
|
|
2040
|
+
issue: writes the number the invoice got in the external system and marks it issued
|
|
2041
|
+
(POST /v1/invoices/:id/issue). --number is unique within the product. --external-ref is any
|
|
2042
|
+
further reference of that system; --document attaches the PDF (at most 5 MB); --issued-at is
|
|
2043
|
+
ISO-8601 with an offset (default: now). Issuing needs confirmation (a prompt on a terminal,
|
|
2044
|
+
otherwise --yes): it is written once and cannot be changed, the customer gets the "invoice
|
|
2045
|
+
issued" email and the product an invoice.issued event.
|
|
2046
|
+
|
|
2047
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
2048
|
+
const WITH_OFFSET = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}(:\d{2}(\.\d+)?)?(Z|[+-]\d{2}:\d{2})$/;
|
|
2049
|
+
const MAX_DOCUMENT_BYTES = 5242880;
|
|
2050
|
+
async function invoicesCommand(ctx, out, args) {
|
|
2051
|
+
const [sub, ...rest] = args;
|
|
2052
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
2053
|
+
out.out(INVOICES_USAGE);
|
|
2054
|
+
return sub === void 0 ? 2 : 0;
|
|
2055
|
+
}
|
|
2056
|
+
if (sub === "list") {
|
|
2057
|
+
const { values, positionals } = parse(rest, {
|
|
2058
|
+
...HELP_OPTION,
|
|
2059
|
+
status: { type: "string" },
|
|
2060
|
+
"payment-status": { type: "string" },
|
|
2061
|
+
from: { type: "string" },
|
|
2062
|
+
to: { type: "string" },
|
|
2063
|
+
limit: { type: "string" },
|
|
2064
|
+
json: { type: "boolean" },
|
|
2065
|
+
csv: { type: "boolean" }
|
|
2066
|
+
}, "invoices");
|
|
2067
|
+
if (values.help) return help$2(out);
|
|
2068
|
+
expectPositionals(positionals, 0, 0, "invoices");
|
|
2069
|
+
if (values.json && values.csv) throw new UsageError("--json and --csv: choose one");
|
|
2070
|
+
if (values.from !== void 0 && !DateTimeSchema.safeParse(values.from).success) throw new UsageError("--from: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z");
|
|
2071
|
+
if (values.to !== void 0 && !DateTimeSchema.safeParse(values.to).success) throw new UsageError("--to: ISO-8601 with an offset, e.g. 2026-10-01T00:00:00Z");
|
|
2072
|
+
const statusText = values.status ?? "draft";
|
|
2073
|
+
const status = statusText === "all" ? void 0 : InvoiceStatusSchema.safeParse(statusText).data;
|
|
2074
|
+
if (statusText !== "all" && status === void 0) throw new UsageError("--status: draft, issued, void or all");
|
|
2075
|
+
const paymentStatus = InvoicePaymentStatusSchema.optional().safeParse(values["payment-status"]);
|
|
2076
|
+
if (!paymentStatus.success) throw new UsageError(`--payment-status: one of ${InvoicePaymentStatusSchema.options.join(", ")}`);
|
|
2077
|
+
const limit = values.limit !== void 0 ? parsePositiveInt(values.limit, "--limit", { max: 500 }) : void 0;
|
|
2078
|
+
const filter = {
|
|
2079
|
+
...status !== void 0 ? { status } : {},
|
|
2080
|
+
...paymentStatus.data !== void 0 ? { paymentStatus: paymentStatus.data } : {},
|
|
2081
|
+
...values.from !== void 0 ? { from: values.from } : {},
|
|
2082
|
+
...values.to !== void 0 ? { to: values.to } : {},
|
|
2083
|
+
...limit !== void 0 ? { limit } : {}
|
|
2084
|
+
};
|
|
2085
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2086
|
+
out.err(connectionLine(target));
|
|
2087
|
+
const { items, hasMore } = await callSteward(target, () => clientFor(ctx, target).admin.invoices.list(filter));
|
|
2088
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
2089
|
+
else if (values.csv) {
|
|
2090
|
+
out.out(INVOICE_EXPORT_COLUMNS.join(","));
|
|
2091
|
+
for (const invoice of items) out.out(invoiceExportRow(invoice).map(csvCell$1).join(","));
|
|
2092
|
+
} else if (items.length === 0) out.out(`no ${status ?? ""} invoices`.replace(" ", " "));
|
|
2093
|
+
else {
|
|
2094
|
+
const rows = [[
|
|
2095
|
+
"CREATED",
|
|
2096
|
+
"STATUS",
|
|
2097
|
+
"NUMBER",
|
|
2098
|
+
"TOTAL",
|
|
2099
|
+
"PAYMENT",
|
|
2100
|
+
"ACCOUNT",
|
|
2101
|
+
"ID"
|
|
2102
|
+
]];
|
|
2103
|
+
for (const i of items) rows.push([
|
|
2104
|
+
i.createdAt,
|
|
2105
|
+
i.status,
|
|
2106
|
+
i.number ?? "-",
|
|
2107
|
+
formatMinor(i.totalMinor, i.currency),
|
|
2108
|
+
i.paymentStatus ?? "-",
|
|
2109
|
+
i.accountRef,
|
|
2110
|
+
i.id
|
|
2111
|
+
]);
|
|
2112
|
+
for (const line of table(rows)) out.out(line);
|
|
2113
|
+
}
|
|
2114
|
+
if (hasMore) out.err(`more invoices than the ${limit ?? 100} listed (--limit, at most 500)`);
|
|
2115
|
+
return 0;
|
|
2116
|
+
}
|
|
2117
|
+
if (sub === "issue") {
|
|
2118
|
+
const { values, positionals } = parse(rest, {
|
|
2119
|
+
...HELP_OPTION,
|
|
2120
|
+
number: { type: "string" },
|
|
2121
|
+
"external-ref": { type: "string" },
|
|
2122
|
+
"issued-at": { type: "string" },
|
|
2123
|
+
document: { type: "string" },
|
|
2124
|
+
yes: {
|
|
2125
|
+
type: "boolean",
|
|
2126
|
+
short: "y"
|
|
2127
|
+
},
|
|
2128
|
+
json: { type: "boolean" }
|
|
2129
|
+
}, "invoices");
|
|
2130
|
+
if (values.help) return help$2(out);
|
|
2131
|
+
expectPositionals(positionals, 1, 1, "invoices");
|
|
2132
|
+
const id = positionals[0];
|
|
2133
|
+
const number = requireOption(values.number, "--number", "invoices").trim();
|
|
2134
|
+
if (values["issued-at"] !== void 0 && !WITH_OFFSET.test(values["issued-at"])) throw new UsageError("--issued-at: ISO-8601 with an offset (2026-09-28T10:15:00+03:00)");
|
|
2135
|
+
const document = values.document !== void 0 ? await readDocument(ctx, values.document) : void 0;
|
|
2136
|
+
const input = {
|
|
2137
|
+
number,
|
|
2138
|
+
...values["external-ref"] !== void 0 ? { externalRef: values["external-ref"] } : {},
|
|
2139
|
+
...values["issued-at"] !== void 0 ? { issuedAt: values["issued-at"] } : {},
|
|
2140
|
+
...document !== void 0 ? { documentBase64: document.toString("base64") } : {}
|
|
2141
|
+
};
|
|
2142
|
+
const parsed = InvoiceIssueInputSchema.safeParse(input);
|
|
2143
|
+
if (!parsed.success) throw new UsageError(`invalid input (nothing was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
2144
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2145
|
+
out.err(connectionLine(target));
|
|
2146
|
+
if (!await confirm(ctx, `Issue invoice ${id} with the number ${number}${document !== void 0 ? " and its document" : ""}? It cannot be changed afterwards and the customer is emailed.`, {
|
|
2147
|
+
yes: values.yes === true,
|
|
2148
|
+
notConfirmed: "nothing was issued"
|
|
2149
|
+
})) {
|
|
2150
|
+
out.err("not confirmed; nothing was issued");
|
|
2151
|
+
return 1;
|
|
2152
|
+
}
|
|
2153
|
+
const issued = await callSteward(target, () => clientFor(ctx, target).invoices.issue(id, input));
|
|
2154
|
+
if (values.json) {
|
|
2155
|
+
const { account: _account, ...invoice } = issued;
|
|
2156
|
+
out.out(JSON.stringify(invoice, null, 2));
|
|
2157
|
+
return 0;
|
|
2158
|
+
}
|
|
2159
|
+
out.out(`issued → ${originOf(target.url)}: invoice ${issued.id} of account ${issued.accountRef}, number ${issued.number}${issued.externalRef !== null ? `, external ref ${issued.externalRef}` : ""}${issued.hasDocument ? ", document stored" : ""}`);
|
|
2160
|
+
return 0;
|
|
2161
|
+
}
|
|
2162
|
+
throw new UsageError(`unknown subcommand: invoices ${sub} (see: steward invoices --help)`);
|
|
2163
|
+
}
|
|
2164
|
+
const INVOICE_EXPORT_COLUMNS = [
|
|
2165
|
+
"id",
|
|
2166
|
+
"number",
|
|
2167
|
+
"status",
|
|
2168
|
+
"createdAt",
|
|
2169
|
+
"issuedAt",
|
|
2170
|
+
"accountRef",
|
|
2171
|
+
"billingReason",
|
|
2172
|
+
"currency",
|
|
2173
|
+
"subtotalMinor",
|
|
2174
|
+
"taxMinor",
|
|
2175
|
+
"totalMinor",
|
|
2176
|
+
"taxRateBps",
|
|
2177
|
+
"taxTreatment",
|
|
2178
|
+
"taxReason",
|
|
2179
|
+
"taxCountry",
|
|
2180
|
+
"periodStart",
|
|
2181
|
+
"periodEnd",
|
|
2182
|
+
"paymentStatus",
|
|
2183
|
+
"paidAt",
|
|
2184
|
+
"paymentMethod",
|
|
2185
|
+
"paymentRef",
|
|
2186
|
+
"buyerKind",
|
|
2187
|
+
"buyerContactName",
|
|
2188
|
+
"buyerCompanyName",
|
|
2189
|
+
"buyerEmail",
|
|
2190
|
+
"buyerPhone",
|
|
2191
|
+
"buyerAddress",
|
|
2192
|
+
"buyerCity",
|
|
2193
|
+
"buyerPostalCode",
|
|
2194
|
+
"buyerRegion",
|
|
2195
|
+
"buyerCountry",
|
|
2196
|
+
"buyerTaxIdType",
|
|
2197
|
+
"buyerTaxId",
|
|
2198
|
+
"buyerTaxOffice",
|
|
2199
|
+
"lines"
|
|
2200
|
+
];
|
|
2201
|
+
function invoiceExportRow(invoice) {
|
|
2202
|
+
const buyer = invoice.buyer;
|
|
2203
|
+
const values = {
|
|
2204
|
+
id: invoice.id,
|
|
2205
|
+
number: invoice.number,
|
|
2206
|
+
status: invoice.status,
|
|
2207
|
+
createdAt: invoice.createdAt,
|
|
2208
|
+
issuedAt: invoice.issuedAt,
|
|
2209
|
+
accountRef: invoice.accountRef,
|
|
2210
|
+
billingReason: invoice.billingReason ?? null,
|
|
2211
|
+
currency: invoice.currency,
|
|
2212
|
+
subtotalMinor: invoice.subtotalMinor,
|
|
2213
|
+
taxMinor: invoice.taxMinor,
|
|
2214
|
+
totalMinor: invoice.totalMinor,
|
|
2215
|
+
taxRateBps: invoice.taxRateBps,
|
|
2216
|
+
taxTreatment: invoice.taxTreatment ?? null,
|
|
2217
|
+
taxReason: invoice.taxReason ?? null,
|
|
2218
|
+
taxCountry: invoice.taxCountry ?? null,
|
|
2219
|
+
periodStart: invoice.periodStart ?? null,
|
|
2220
|
+
periodEnd: invoice.periodEnd ?? null,
|
|
2221
|
+
paymentStatus: invoice.paymentStatus ?? null,
|
|
2222
|
+
paidAt: invoice.paidAt ?? null,
|
|
2223
|
+
paymentMethod: invoice.paymentMethod ?? null,
|
|
2224
|
+
paymentRef: invoice.paymentRef ?? null,
|
|
2225
|
+
buyerKind: buyer.kind,
|
|
2226
|
+
buyerContactName: buyer.contactName,
|
|
2227
|
+
buyerCompanyName: buyer.companyName ?? null,
|
|
2228
|
+
buyerEmail: buyer.email,
|
|
2229
|
+
buyerPhone: buyer.phone,
|
|
2230
|
+
buyerAddress: buyer.address,
|
|
2231
|
+
buyerCity: buyer.city,
|
|
2232
|
+
buyerPostalCode: buyer.postalCode ?? null,
|
|
2233
|
+
buyerRegion: buyer.region ?? null,
|
|
2234
|
+
buyerCountry: buyer.country,
|
|
2235
|
+
buyerTaxIdType: buyer.taxId !== void 0 ? taxIdTypeOf(buyer.country, buyer.taxIdType) : null,
|
|
2236
|
+
buyerTaxId: buyer.taxId ?? null,
|
|
2237
|
+
buyerTaxOffice: buyer.taxOffice ?? null,
|
|
2238
|
+
lines: JSON.stringify(invoice.lines.map((line) => ({
|
|
2239
|
+
description: line.description,
|
|
2240
|
+
quantity: line.quantity,
|
|
2241
|
+
unitAmountMinor: line.unitAmountMinor,
|
|
2242
|
+
amountMinor: line.amountMinor
|
|
2243
|
+
})))
|
|
2244
|
+
};
|
|
2245
|
+
return INVOICE_EXPORT_COLUMNS.map((column) => values[column]);
|
|
2246
|
+
}
|
|
2247
|
+
const csvCell$1 = (value) => {
|
|
2248
|
+
const cell = value === null ? "" : String(value);
|
|
2249
|
+
return /[",\n\r]/.test(cell) ? `"${cell.replace(/"/g, "\"\"")}"` : cell;
|
|
2250
|
+
};
|
|
2251
|
+
/** Reads the PDF to attach; the same checks as steward's (PDF signature, at most 5 MB) before anything is sent. */
|
|
2252
|
+
async function readDocument(ctx, file) {
|
|
2253
|
+
let bytes;
|
|
2254
|
+
try {
|
|
2255
|
+
bytes = await readFile(resolve(ctx.cwd, file));
|
|
2256
|
+
} catch (error) {
|
|
2257
|
+
throw new UsageError(`--document: cannot read ${file} (${errnoCode(error) ?? "error"})`);
|
|
2258
|
+
}
|
|
2259
|
+
if (bytes.subarray(0, 5).toString("latin1") !== "%PDF-") throw new UsageError(`--document: ${file} is not a PDF`);
|
|
2260
|
+
if (bytes.length > MAX_DOCUMENT_BYTES) throw new UsageError(`--document: ${file} is larger than 5 MB`);
|
|
2261
|
+
return bytes;
|
|
2262
|
+
}
|
|
2263
|
+
function help$2(out) {
|
|
2264
|
+
out.out(INVOICES_USAGE);
|
|
2265
|
+
return 0;
|
|
2266
|
+
}
|
|
2267
|
+
// src/commands/keys.ts
|
|
1941
2268
|
const KEYS_USAGE = `Usage:
|
|
1942
2269
|
steward keys list [--json]
|
|
1943
2270
|
steward keys create --name <name> --scope product|checkout|admin --out <file>
|
|
@@ -1975,7 +2302,7 @@ async function keysCommand(ctx, out, args) {
|
|
|
1975
2302
|
...HELP_OPTION,
|
|
1976
2303
|
json: { type: "boolean" }
|
|
1977
2304
|
}, "keys");
|
|
1978
|
-
if (values.help) return help(out);
|
|
2305
|
+
if (values.help) return help$1(out);
|
|
1979
2306
|
expectPositionals(positionals, 0, 0, "keys");
|
|
1980
2307
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
1981
2308
|
out.err(connectionLine(target));
|
|
@@ -2013,7 +2340,7 @@ async function keysCommand(ctx, out, args) {
|
|
|
2013
2340
|
"no-expiry": { type: "boolean" },
|
|
2014
2341
|
force: { type: "boolean" }
|
|
2015
2342
|
}, "keys");
|
|
2016
|
-
if (values.help) return help(out);
|
|
2343
|
+
if (values.help) return help$1(out);
|
|
2017
2344
|
expectPositionals(positionals, 0, 0, "keys");
|
|
2018
2345
|
const name = requireOption(values.name, "--name", "keys");
|
|
2019
2346
|
const scope = requireOption(values.scope, "--scope", "keys");
|
|
@@ -2044,7 +2371,7 @@ async function keysCommand(ctx, out, args) {
|
|
|
2044
2371
|
}
|
|
2045
2372
|
if (sub === "revoke") {
|
|
2046
2373
|
const { values, positionals } = parse(rest, { ...HELP_OPTION }, "keys");
|
|
2047
|
-
if (values.help) return help(out);
|
|
2374
|
+
if (values.help) return help$1(out);
|
|
2048
2375
|
expectPositionals(positionals, 1, 1, "keys");
|
|
2049
2376
|
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2050
2377
|
out.err(connectionLine(target));
|
|
@@ -2054,12 +2381,11 @@ async function keysCommand(ctx, out, args) {
|
|
|
2054
2381
|
}
|
|
2055
2382
|
throw new UsageError(`unknown subcommand: keys ${sub} (see: steward keys --help)`);
|
|
2056
2383
|
}
|
|
2057
|
-
function help(out) {
|
|
2384
|
+
function help$1(out) {
|
|
2058
2385
|
out.out(KEYS_USAGE);
|
|
2059
2386
|
return 0;
|
|
2060
2387
|
}
|
|
2061
|
-
|
|
2062
|
-
//#region src/commands/reprice.ts
|
|
2388
|
+
// src/commands/reprice.ts
|
|
2063
2389
|
const REPRICE_USAGE = `Usage: steward reprice --plan <code> --notice-days <n> [--dry-run] [--yes] [--json]
|
|
2064
2390
|
|
|
2065
2391
|
Moves the live subscriptions of a plan to the plan's current price and metered rates
|
|
@@ -2147,19 +2473,24 @@ async function repriceCommand(ctx, out, args) {
|
|
|
2147
2473
|
else out.out(`scheduled → ${originOf(target.url)}: ${result.scheduled} subscription${result.scheduled === 1 ? "" : "s"} (one notice e-mail each)`);
|
|
2148
2474
|
return 0;
|
|
2149
2475
|
}
|
|
2150
|
-
|
|
2151
|
-
//#region src/commands/settings.ts
|
|
2476
|
+
// src/commands/settings.ts
|
|
2152
2477
|
const SETTINGS_USAGE = `Usage:
|
|
2153
2478
|
steward settings get
|
|
2154
2479
|
steward settings set [--app-url <url>] [--privacy-url <url>] [--terms-url <url>]
|
|
2155
|
-
[--branding <json>] [--default-locale tr|en]
|
|
2480
|
+
[--branding <json>] [--default-locale tr|en] [--display-time-zone <iana>]
|
|
2481
|
+
[--default-country <XX>]
|
|
2156
2482
|
[--checkout-ttl <minutes>] [--portal-ttl <minutes>]
|
|
2157
2483
|
[--extra-return-origins <a,b>] [--emails <json>]
|
|
2158
2484
|
[--billing-payment-due-days <1-60>] [--billing-min-invoice-minor <n>]
|
|
2159
2485
|
[--billing-allow-multiple-subscriptions true|false]
|
|
2486
|
+
[--billing-renewal-notice-intervals <year,month>] [--billing-renewal-notice-days <1-90>]
|
|
2487
|
+
[--billing-invoice-line-text iso|localized]
|
|
2160
2488
|
[--metering-charge-mode off|dry_run|live]
|
|
2161
2489
|
[--metering-late-grace-minutes <0-1440>] [--events-retention-days <45-400>]
|
|
2162
2490
|
[--provider <id>]
|
|
2491
|
+
[--tax-provider price|none] [--tax-exemption-reason-en <text>]
|
|
2492
|
+
[--tax-exemption-reason-tr <text>] [--consumer-markets <XX,YY>]
|
|
2493
|
+
[--seller <json>] [--withdrawal-waiver <json>] [--card-on-file <json>]
|
|
2163
2494
|
|
|
2164
2495
|
Product settings (GET/PATCH /v1/admin/settings). A field not given is unchanged; an
|
|
2165
2496
|
empty value (--privacy-url "") clears the field, --branding null clears the branding,
|
|
@@ -2173,15 +2504,41 @@ invoice to its due date (default 7), --billing-min-invoice-minor smallest amount
|
|
|
2173
2504
|
steward invoices on its own, in minor units (default 1000), and
|
|
2174
2505
|
--billing-allow-multiple-subscriptions (default false: a checkout for an account with
|
|
2175
2506
|
a live subscription is 409 already_subscribed; true: only a second subscription to the
|
|
2176
|
-
same plan is).
|
|
2507
|
+
same plan is). --billing-renewal-notice-intervals lists the plan intervals that get the
|
|
2508
|
+
renewal notice e-mail (e.g. year; default none: no notice) and --billing-renewal-notice-days
|
|
2509
|
+
how many days before the renewal it is sent (default 30). --billing-invoice-line-text decides
|
|
2510
|
+
how new invoice lines are written: iso (default) ISO dates and the product's default language,
|
|
2511
|
+
localized the buyer's language with dates written in it. An empty value ("") restores the
|
|
2512
|
+
field's default.
|
|
2177
2513
|
Metering (settings.metering, settings.events): --metering-charge-mode prices overage
|
|
2178
2514
|
at the end of a usage period: dry_run (default) records the charge without invoicing
|
|
2179
2515
|
it, live adds it to the renewal invoice, off prices nothing — run one full cycle in
|
|
2180
2516
|
dry_run before live. --metering-late-grace-minutes how long a period waits for late
|
|
2181
2517
|
events before it closes (default 60). --events-retention-days how long raw events are
|
|
2182
2518
|
kept after receipt, once their period is closed (default 120). "" restores the default.
|
|
2519
|
+
--default-locale is the language of hosted pages and emails when the call, the session and
|
|
2520
|
+
the account name none steward supports. --display-time-zone is the IANA zone customer-facing
|
|
2521
|
+
dates are shown in (default Europe/Istanbul; a time of day names the zone); "" restores it.
|
|
2522
|
+
--default-country is the ISO country code (e.g. TR, DE, US) the hosted checkout and portal
|
|
2523
|
+
forms start on when the buyer has no stored profile (default TR); "" restores the default.
|
|
2183
2524
|
--provider sets the payment provider for NEW checkouts and payment sessions (open ones keep
|
|
2184
2525
|
theirs); steward accepts only a provider configured in its deployment (iyzico, fake…).
|
|
2526
|
+
Tax (settings.tax): --tax-provider decides the tax of invoices written from now on: price
|
|
2527
|
+
(default) the price's own rate; none no tax charged, every invoice exempt with the exemption
|
|
2528
|
+
wording (while the seller is under its thresholds; see steward tax --help).
|
|
2529
|
+
--tax-exemption-reason-en / -tr is that wording per language (the seller's legal wording; doctor
|
|
2530
|
+
warns while the provider is none and it is unset). --consumer-markets lists the countries open
|
|
2531
|
+
to individual buyers (e.g. AT,BE,…,US): a consumer elsewhere is refused at checkout, a business
|
|
2532
|
+
buyer never; "" opens every country (the default). "" restores a field's default.
|
|
2533
|
+
Legal (settings.legal; the texts are the seller's own, steward ships none; each is replaced as a
|
|
2534
|
+
whole, "" or null removes it): --seller is the seller's identity shown in the footer of hosted
|
|
2535
|
+
pages and e-mails, '{"legalName":"Acme Ltd","address":"1 Example Street, Example City",
|
|
2536
|
+
"taxId":"XX123456789","registrationNumber":"12345678"}'.
|
|
2537
|
+
--withdrawal-waiver is the checkbox consumers tick at checkout to waive the right of withdrawal,
|
|
2538
|
+
'{"version":"2026-10","text":{"en":"…"},"url":"https://…","countries":["DE","FR"]}' (countries
|
|
2539
|
+
empty or left out: every consumer). --card-on-file is the checkbox a card payer ticks when the
|
|
2540
|
+
card is saved for renewals (Stripe), '{"version":"2026-10","text":{"en":"…"}}'. Each acceptance
|
|
2541
|
+
is recorded with the version.
|
|
2185
2542
|
|
|
2186
2543
|
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
2187
2544
|
const SET_OPTIONS = {
|
|
@@ -2191,6 +2548,8 @@ const SET_OPTIONS = {
|
|
|
2191
2548
|
"terms-url": { type: "string" },
|
|
2192
2549
|
branding: { type: "string" },
|
|
2193
2550
|
"default-locale": { type: "string" },
|
|
2551
|
+
"display-time-zone": { type: "string" },
|
|
2552
|
+
"default-country": { type: "string" },
|
|
2194
2553
|
"checkout-ttl": { type: "string" },
|
|
2195
2554
|
"portal-ttl": { type: "string" },
|
|
2196
2555
|
"extra-return-origins": { type: "string" },
|
|
@@ -2198,12 +2557,35 @@ const SET_OPTIONS = {
|
|
|
2198
2557
|
"billing-payment-due-days": { type: "string" },
|
|
2199
2558
|
"billing-min-invoice-minor": { type: "string" },
|
|
2200
2559
|
"billing-allow-multiple-subscriptions": { type: "string" },
|
|
2560
|
+
"billing-renewal-notice-intervals": { type: "string" },
|
|
2561
|
+
"billing-renewal-notice-days": { type: "string" },
|
|
2562
|
+
"billing-invoice-line-text": { type: "string" },
|
|
2201
2563
|
"metering-charge-mode": { type: "string" },
|
|
2202
2564
|
"metering-late-grace-minutes": { type: "string" },
|
|
2203
2565
|
"events-retention-days": { type: "string" },
|
|
2204
|
-
provider: { type: "string" }
|
|
2566
|
+
provider: { type: "string" },
|
|
2567
|
+
"tax-provider": { type: "string" },
|
|
2568
|
+
"tax-exemption-reason-en": { type: "string" },
|
|
2569
|
+
"tax-exemption-reason-tr": { type: "string" },
|
|
2570
|
+
"consumer-markets": { type: "string" },
|
|
2571
|
+
seller: { type: "string" },
|
|
2572
|
+
"withdrawal-waiver": { type: "string" },
|
|
2573
|
+
"card-on-file": { type: "string" }
|
|
2205
2574
|
};
|
|
2206
2575
|
const orNull = (value) => value.trim() === "" ? null : value.trim();
|
|
2576
|
+
/** A JSON object flag; "" or null → null (clear). */
|
|
2577
|
+
function jsonObjectOrNull(value, flag) {
|
|
2578
|
+
const text = value.trim();
|
|
2579
|
+
if (text === "" || text === "null") return null;
|
|
2580
|
+
let parsed;
|
|
2581
|
+
try {
|
|
2582
|
+
parsed = JSON.parse(text);
|
|
2583
|
+
} catch {
|
|
2584
|
+
throw new UsageError(`--${flag}: must be a JSON object (see steward settings --help)`);
|
|
2585
|
+
}
|
|
2586
|
+
if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) throw new UsageError(`--${flag}: must be a JSON object`);
|
|
2587
|
+
return parsed;
|
|
2588
|
+
}
|
|
2207
2589
|
/** A patch from the flags; validated with the contract schema (if invalid no request is sent). */
|
|
2208
2590
|
function buildSettingsPatch(values) {
|
|
2209
2591
|
const patch = {};
|
|
@@ -2239,6 +2621,8 @@ function buildSettingsPatch(values) {
|
|
|
2239
2621
|
}
|
|
2240
2622
|
}
|
|
2241
2623
|
if (values["default-locale"] !== void 0) patch.defaultLocale = values["default-locale"].trim();
|
|
2624
|
+
if (values["display-time-zone"] !== void 0) patch.displayTimeZone = orNull(values["display-time-zone"]);
|
|
2625
|
+
if (values["default-country"] !== void 0) patch.defaultCountry = orNull(values["default-country"])?.toUpperCase() ?? null;
|
|
2242
2626
|
if (values.provider !== void 0) patch.provider = values.provider.trim();
|
|
2243
2627
|
if (values["checkout-ttl"] !== void 0) patch.checkoutTtlMinutes = parsePositiveInt(values["checkout-ttl"], "--checkout-ttl");
|
|
2244
2628
|
if (values["portal-ttl"] !== void 0) patch.portalTtlMinutes = parsePositiveInt(values["portal-ttl"], "--portal-ttl");
|
|
@@ -2250,6 +2634,18 @@ function buildSettingsPatch(values) {
|
|
|
2250
2634
|
if (minInvoice !== void 0) billing.minInvoiceMinor = minInvoice.trim() === "" ? null : parseNonNegativeInt(minInvoice, "--billing-min-invoice-minor");
|
|
2251
2635
|
const multiple = values["billing-allow-multiple-subscriptions"];
|
|
2252
2636
|
if (multiple !== void 0) billing.allowMultipleSubscriptions = multiple.trim() === "" ? null : parseBoolean(multiple, "--billing-allow-multiple-subscriptions");
|
|
2637
|
+
const renewalNotice = {};
|
|
2638
|
+
const noticeIntervals = values["billing-renewal-notice-intervals"];
|
|
2639
|
+
if (noticeIntervals !== void 0) renewalNotice.intervals = noticeIntervals.trim() === "" ? null : parseList(noticeIntervals);
|
|
2640
|
+
const noticeDays = values["billing-renewal-notice-days"];
|
|
2641
|
+
if (noticeDays !== void 0) renewalNotice.daysBefore = noticeDays.trim() === "" ? null : parsePositiveInt(noticeDays, "--billing-renewal-notice-days", { max: 90 });
|
|
2642
|
+
if (Object.keys(renewalNotice).length > 0) billing.renewalNotice = renewalNotice;
|
|
2643
|
+
const lineText = values["billing-invoice-line-text"];
|
|
2644
|
+
if (lineText !== void 0) {
|
|
2645
|
+
const style = lineText.trim();
|
|
2646
|
+
if (style !== "" && !INVOICE_LINE_TEXTS.includes(style)) throw new UsageError(`--billing-invoice-line-text: one of ${INVOICE_LINE_TEXTS.join(", ")}`);
|
|
2647
|
+
billing.invoiceLineText = style === "" ? null : style;
|
|
2648
|
+
}
|
|
2253
2649
|
if (Object.keys(billing).length > 0) patch.billing = billing;
|
|
2254
2650
|
const metering = {};
|
|
2255
2651
|
const chargeMode = values["metering-charge-mode"];
|
|
@@ -2263,6 +2659,27 @@ function buildSettingsPatch(values) {
|
|
|
2263
2659
|
if (Object.keys(metering).length > 0) patch.metering = metering;
|
|
2264
2660
|
const retention = values["events-retention-days"];
|
|
2265
2661
|
if (retention !== void 0) patch.events = { retentionDays: retention.trim() === "" ? null : parsePositiveInt(retention, "--events-retention-days", { max: 400 }) };
|
|
2662
|
+
const tax = {};
|
|
2663
|
+
const taxProvider = values["tax-provider"];
|
|
2664
|
+
if (taxProvider !== void 0) {
|
|
2665
|
+
const id = taxProvider.trim();
|
|
2666
|
+
if (id !== "" && !TAX_PROVIDERS.includes(id)) throw new UsageError(`--tax-provider: one of ${TAX_PROVIDERS.join(", ")}`);
|
|
2667
|
+
tax.provider = id === "" ? null : id;
|
|
2668
|
+
}
|
|
2669
|
+
const reasons = {};
|
|
2670
|
+
for (const locale of ["en", "tr"]) {
|
|
2671
|
+
const reason = values[`tax-exemption-reason-${locale}`];
|
|
2672
|
+
if (reason !== void 0) reasons[locale] = orNull(reason);
|
|
2673
|
+
}
|
|
2674
|
+
if (Object.keys(reasons).length > 0) tax.exemptionReason = reasons;
|
|
2675
|
+
const markets = values["consumer-markets"];
|
|
2676
|
+
if (markets !== void 0) tax.consumerMarkets = markets.trim() === "" ? null : parseList(markets).map((country) => country.toUpperCase());
|
|
2677
|
+
if (Object.keys(tax).length > 0) patch.tax = tax;
|
|
2678
|
+
const legal = {};
|
|
2679
|
+
if (values.seller !== void 0) legal.seller = jsonObjectOrNull(values.seller, "seller");
|
|
2680
|
+
if (values["withdrawal-waiver"] !== void 0) legal.withdrawalWaiver = jsonObjectOrNull(values["withdrawal-waiver"], "withdrawal-waiver");
|
|
2681
|
+
if (values["card-on-file"] !== void 0) legal.cardOnFile = jsonObjectOrNull(values["card-on-file"], "card-on-file");
|
|
2682
|
+
if (Object.keys(legal).length > 0) patch.legal = legal;
|
|
2266
2683
|
if (Object.keys(patch).length === 0) throw new UsageError(`at least one settings flag is required (details: steward settings --help)`);
|
|
2267
2684
|
const parsed = ProductSettingsPatchSchema.safeParse(patch);
|
|
2268
2685
|
if (!parsed.success) throw new UsageError(`invalid settings (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}`);
|
|
@@ -2306,9 +2723,244 @@ async function settingsCommand(ctx, out, args) {
|
|
|
2306
2723
|
}
|
|
2307
2724
|
throw new UsageError(`unknown subcommand: settings ${sub} (details: steward settings --help)`);
|
|
2308
2725
|
}
|
|
2309
|
-
|
|
2310
|
-
|
|
2311
|
-
|
|
2726
|
+
// src/commands/tax.ts
|
|
2727
|
+
const TAX_USAGE = `Usage:
|
|
2728
|
+
steward tax thresholds list [--json]
|
|
2729
|
+
steward tax thresholds set <code> --scope <scope> --currency <XXX>
|
|
2730
|
+
[--amount-minor <n>] [--transactions <n>]
|
|
2731
|
+
[--country <XX>] [--region <XX>] [--home-country <XX>]
|
|
2732
|
+
[--period calendar_year|rolling_12_months] [--warn-at-bps <1-10000>]
|
|
2733
|
+
[--fx-rate <XXX>=<rate> ...] [--note <text>]
|
|
2734
|
+
steward tax thresholds delete <code>
|
|
2735
|
+
steward tax sales [--from <iso>] [--to <iso>] [--json | --csv]
|
|
2736
|
+
|
|
2737
|
+
Tax registration thresholds and the sales they count (/v1/admin/tax/thresholds,
|
|
2738
|
+
/v1/admin/sales). Steward ships with no threshold: the seller's tax adviser decides which apply,
|
|
2739
|
+
how much and how they are counted; enter each with "set".
|
|
2740
|
+
|
|
2741
|
+
Scopes (--scope): company_turnover (every paid sale), eu_cross_border_consumer (individual
|
|
2742
|
+
buyers in an EU member state other than --home-country, the seller's), country (buyers in
|
|
2743
|
+
--country), us_state (buyers in the US state --region, e.g. CA). A threshold has an amount
|
|
2744
|
+
(--amount-minor, minor units of --currency), a number of sales (--transactions) or both; it
|
|
2745
|
+
counts its --period (default calendar_year, UTC) and warns at --warn-at-bps of its limit
|
|
2746
|
+
(default 8000 = 80%). Sales in another currency count at --fx-rate (units of --currency per 1
|
|
2747
|
+
unit of the sale's, e.g. --fx-rate USD=0.92 --fx-rate GBP=1.17); without a rate they are not
|
|
2748
|
+
counted and doctor warns. "set" replaces the whole threshold; every change is audited.
|
|
2749
|
+
|
|
2750
|
+
A sale is a payment steward collected, by its date, attributed to the buyer's declared country
|
|
2751
|
+
and region on the invoice it paid, net of refunds.
|
|
2752
|
+
|
|
2753
|
+
sales: paid sales per UTC month, buyer country, region, buyer kind, currency and tax treatment,
|
|
2754
|
+
with counts and totals (the threshold evidence). --from inclusive, --to exclusive (ISO-8601 with
|
|
2755
|
+
an offset); default: this calendar year up to now; at most ${SALES_REPORT_MAX_MONTHS} months.
|
|
2756
|
+
|
|
2757
|
+
Connection: STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY (environment, otherwise ./.env.local).`;
|
|
2758
|
+
const percent = (bps) => bps === null ? "-" : `${(bps / 100).toFixed(2)}%`;
|
|
2759
|
+
function scopeText(t) {
|
|
2760
|
+
switch (t.scope) {
|
|
2761
|
+
case "country": return `country ${t.country}`;
|
|
2762
|
+
case "us_state": return `us_state ${t.region}`;
|
|
2763
|
+
case "eu_cross_border_consumer": return `eu_cross_border_consumer (home ${t.homeCountry})`;
|
|
2764
|
+
default: return t.scope;
|
|
2765
|
+
}
|
|
2766
|
+
}
|
|
2767
|
+
function limitText(t) {
|
|
2768
|
+
return [t.amountMinor !== null ? `${t.amountMinor} ${t.currency}` : null, t.transactions !== null ? `${t.transactions} sales` : null].filter((part) => part !== null).join(" / ");
|
|
2769
|
+
}
|
|
2770
|
+
/** `USD=0.92` flags → the rates map (the contract checks each rate). */
|
|
2771
|
+
function parseFxRates(values) {
|
|
2772
|
+
const rates = {};
|
|
2773
|
+
for (const value of values ?? []) {
|
|
2774
|
+
const match = /^([A-Za-z]{3})=(.+)$/.exec(value.trim());
|
|
2775
|
+
if (!match) throw new UsageError("--fx-rate: <currency>=<rate>, e.g. USD=0.92");
|
|
2776
|
+
rates[match[1].toUpperCase()] = match[2].trim();
|
|
2777
|
+
}
|
|
2778
|
+
return rates;
|
|
2779
|
+
}
|
|
2780
|
+
/** The threshold from the flags; validated with the contract schema (if invalid no request is sent). */
|
|
2781
|
+
function buildThresholdInput(values) {
|
|
2782
|
+
const text = (name) => typeof values[name] === "string" ? values[name].trim() : void 0;
|
|
2783
|
+
const input = {
|
|
2784
|
+
scope: text("scope"),
|
|
2785
|
+
currency: text("currency")?.toUpperCase(),
|
|
2786
|
+
fxRates: parseFxRates(values["fx-rate"])
|
|
2787
|
+
};
|
|
2788
|
+
const amount = text("amount-minor");
|
|
2789
|
+
if (amount !== void 0) input.amountMinor = parsePositiveInt(amount, "--amount-minor");
|
|
2790
|
+
const transactions = text("transactions");
|
|
2791
|
+
if (transactions !== void 0) input.transactions = parsePositiveInt(transactions, "--transactions");
|
|
2792
|
+
if (text("country") !== void 0) input.country = text("country").toUpperCase();
|
|
2793
|
+
if (text("region") !== void 0) input.region = text("region").toUpperCase();
|
|
2794
|
+
if (text("home-country") !== void 0) input.homeCountry = text("home-country").toUpperCase();
|
|
2795
|
+
if (text("period") !== void 0) input.period = text("period");
|
|
2796
|
+
const warnAt = text("warn-at-bps");
|
|
2797
|
+
if (warnAt !== void 0) input.warnAtBps = parsePositiveInt(warnAt, "--warn-at-bps", { max: 1e4 });
|
|
2798
|
+
if (text("note") !== void 0) input.note = text("note");
|
|
2799
|
+
const parsed = TaxThresholdInputSchema.safeParse(input);
|
|
2800
|
+
if (!parsed.success) throw new UsageError(`invalid threshold (no request was sent)\n${parsed.error.issues.map((issue) => ` - ${issue.path.map(String).join(".") || "(root)"}: ${issue.message}`).join("\n")}\nscopes: ${TAX_THRESHOLD_SCOPES.join(", ")}; periods: ${TAX_THRESHOLD_PERIODS.join(", ")}`);
|
|
2801
|
+
return input;
|
|
2802
|
+
}
|
|
2803
|
+
const csvCell = (value) => {
|
|
2804
|
+
const cell = value === null ? "" : String(value);
|
|
2805
|
+
return /[",\n]/.test(cell) ? `"${cell.replace(/"/g, "\"\"")}"` : cell;
|
|
2806
|
+
};
|
|
2807
|
+
const SALES_COLUMNS = [
|
|
2808
|
+
"month",
|
|
2809
|
+
"country",
|
|
2810
|
+
"region",
|
|
2811
|
+
"buyerKind",
|
|
2812
|
+
"currency",
|
|
2813
|
+
"taxTreatment",
|
|
2814
|
+
"sales",
|
|
2815
|
+
"amountMinor",
|
|
2816
|
+
"taxMinor",
|
|
2817
|
+
"refundedMinor"
|
|
2818
|
+
];
|
|
2819
|
+
function salesRow(item) {
|
|
2820
|
+
return SALES_COLUMNS.map((column) => item[column]);
|
|
2821
|
+
}
|
|
2822
|
+
async function taxCommand(ctx, out, args) {
|
|
2823
|
+
const [sub, ...rest] = args;
|
|
2824
|
+
if (sub === void 0 || sub === "--help" || sub === "-h" || sub === "help") {
|
|
2825
|
+
out.out(TAX_USAGE);
|
|
2826
|
+
return sub === void 0 ? 2 : 0;
|
|
2827
|
+
}
|
|
2828
|
+
if (sub === "thresholds") {
|
|
2829
|
+
const [action, ...more] = rest;
|
|
2830
|
+
if (action === "list") {
|
|
2831
|
+
const { values, positionals } = parse(more, {
|
|
2832
|
+
...HELP_OPTION,
|
|
2833
|
+
json: { type: "boolean" }
|
|
2834
|
+
}, "tax");
|
|
2835
|
+
if (values.help) return help(out);
|
|
2836
|
+
expectPositionals(positionals, 0, 0, "tax");
|
|
2837
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2838
|
+
out.err(connectionLine(target));
|
|
2839
|
+
const { items } = await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.list());
|
|
2840
|
+
if (values.json) out.out(JSON.stringify(items, null, 2));
|
|
2841
|
+
else if (items.length === 0) out.out("no tax thresholds (enter the ones that apply: steward tax thresholds set --help)");
|
|
2842
|
+
else {
|
|
2843
|
+
const rows = [[
|
|
2844
|
+
"CODE",
|
|
2845
|
+
"SCOPE",
|
|
2846
|
+
"LIMIT",
|
|
2847
|
+
"PERIOD",
|
|
2848
|
+
"COUNTED",
|
|
2849
|
+
"AMOUNT",
|
|
2850
|
+
"SALES",
|
|
2851
|
+
"STATUS"
|
|
2852
|
+
]];
|
|
2853
|
+
for (const t of items) rows.push([
|
|
2854
|
+
t.code,
|
|
2855
|
+
scopeText(t),
|
|
2856
|
+
limitText(t),
|
|
2857
|
+
`${t.usage.from.slice(0, 10)} – ${t.usage.to.slice(0, 10)}`,
|
|
2858
|
+
`${t.usage.amountMinor} ${t.currency} / ${t.usage.transactions} sales`,
|
|
2859
|
+
percent(t.usage.amountShareBps),
|
|
2860
|
+
percent(t.usage.transactionShareBps),
|
|
2861
|
+
t.usage.status
|
|
2862
|
+
]);
|
|
2863
|
+
for (const line of table(rows)) out.out(line);
|
|
2864
|
+
for (const t of items) for (const u of t.usage.unconverted) out.err(`${t.code}: ${u.transactions} sale(s) in ${u.currency} (${u.amountMinor}) not counted: no --fx-rate ${u.currency}=…`);
|
|
2865
|
+
}
|
|
2866
|
+
return 0;
|
|
2867
|
+
}
|
|
2868
|
+
if (action === "set") {
|
|
2869
|
+
const { values, positionals } = parse(more, {
|
|
2870
|
+
...HELP_OPTION,
|
|
2871
|
+
scope: { type: "string" },
|
|
2872
|
+
currency: { type: "string" },
|
|
2873
|
+
"amount-minor": { type: "string" },
|
|
2874
|
+
transactions: { type: "string" },
|
|
2875
|
+
country: { type: "string" },
|
|
2876
|
+
region: { type: "string" },
|
|
2877
|
+
"home-country": { type: "string" },
|
|
2878
|
+
period: { type: "string" },
|
|
2879
|
+
"warn-at-bps": { type: "string" },
|
|
2880
|
+
"fx-rate": {
|
|
2881
|
+
type: "string",
|
|
2882
|
+
multiple: true
|
|
2883
|
+
},
|
|
2884
|
+
note: { type: "string" }
|
|
2885
|
+
}, "tax");
|
|
2886
|
+
if (values.help) return help(out);
|
|
2887
|
+
expectPositionals(positionals, 1, 1, "tax");
|
|
2888
|
+
const code = positionals[0];
|
|
2889
|
+
if (!CodeSchema.safeParse(code).success) throw new UsageError("<code>: lowercase letters, digits and _ (e.g. small_business)");
|
|
2890
|
+
const input = buildThresholdInput(values);
|
|
2891
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2892
|
+
out.err(connectionLine(target));
|
|
2893
|
+
const stored = await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.set(code, input));
|
|
2894
|
+
out.err(`threshold ${code} stored → ${originOf(target.url)}`);
|
|
2895
|
+
out.out(JSON.stringify(stored, null, 2));
|
|
2896
|
+
return 0;
|
|
2897
|
+
}
|
|
2898
|
+
if (action === "delete") {
|
|
2899
|
+
const { values, positionals } = parse(more, { ...HELP_OPTION }, "tax");
|
|
2900
|
+
if (values.help) return help(out);
|
|
2901
|
+
expectPositionals(positionals, 1, 1, "tax");
|
|
2902
|
+
const code = positionals[0];
|
|
2903
|
+
if (!CodeSchema.safeParse(code).success) throw new UsageError("<code>: lowercase letters, digits and _");
|
|
2904
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2905
|
+
out.err(connectionLine(target));
|
|
2906
|
+
await callSteward(target, () => clientFor(ctx, target).admin.tax.thresholds.delete(code));
|
|
2907
|
+
out.out(`threshold ${code} deleted → ${originOf(target.url)}`);
|
|
2908
|
+
return 0;
|
|
2909
|
+
}
|
|
2910
|
+
throw new UsageError(`unknown subcommand: tax thresholds${action !== void 0 ? ` ${action}` : ""} (see: steward tax --help)`);
|
|
2911
|
+
}
|
|
2912
|
+
if (sub === "sales") {
|
|
2913
|
+
const { values, positionals } = parse(rest, {
|
|
2914
|
+
...HELP_OPTION,
|
|
2915
|
+
from: { type: "string" },
|
|
2916
|
+
to: { type: "string" },
|
|
2917
|
+
json: { type: "boolean" },
|
|
2918
|
+
csv: { type: "boolean" }
|
|
2919
|
+
}, "tax");
|
|
2920
|
+
if (values.help) return help(out);
|
|
2921
|
+
expectPositionals(positionals, 0, 0, "tax");
|
|
2922
|
+
if (values.json && values.csv) throw new UsageError("--json and --csv: choose one");
|
|
2923
|
+
if (values.from !== void 0 && !DateTimeSchema.safeParse(values.from).success) throw new UsageError("--from: ISO-8601 with an offset, e.g. 2026-01-01T00:00:00Z");
|
|
2924
|
+
if (values.to !== void 0 && !DateTimeSchema.safeParse(values.to).success) throw new UsageError("--to: ISO-8601 with an offset, e.g. 2026-01-01T00:00:00Z");
|
|
2925
|
+
const range = {
|
|
2926
|
+
...values.from !== void 0 ? { from: values.from } : {},
|
|
2927
|
+
...values.to !== void 0 ? { to: values.to } : {}
|
|
2928
|
+
};
|
|
2929
|
+
const target = requireAdminTarget(await resolveEnv(ctx));
|
|
2930
|
+
out.err(connectionLine(target));
|
|
2931
|
+
const report = await callSteward(target, () => clientFor(ctx, target).admin.tax.sales(range));
|
|
2932
|
+
out.err(`sales ${report.from} – ${report.to}`);
|
|
2933
|
+
if (values.json) out.out(JSON.stringify(report, null, 2));
|
|
2934
|
+
else if (values.csv) {
|
|
2935
|
+
out.out(SALES_COLUMNS.join(","));
|
|
2936
|
+
for (const item of report.items) out.out(salesRow(item).map(csvCell).join(","));
|
|
2937
|
+
} else if (report.items.length === 0) out.out("no paid sales in the period");
|
|
2938
|
+
else {
|
|
2939
|
+
const rows = [[
|
|
2940
|
+
"MONTH",
|
|
2941
|
+
"COUNTRY",
|
|
2942
|
+
"REGION",
|
|
2943
|
+
"KIND",
|
|
2944
|
+
"CURRENCY",
|
|
2945
|
+
"TREATMENT",
|
|
2946
|
+
"SALES",
|
|
2947
|
+
"AMOUNT",
|
|
2948
|
+
"TAX",
|
|
2949
|
+
"REFUNDED"
|
|
2950
|
+
]];
|
|
2951
|
+
for (const item of report.items) rows.push(salesRow(item).map((cell) => cell === null ? "-" : String(cell)));
|
|
2952
|
+
for (const line of table(rows)) out.out(line);
|
|
2953
|
+
}
|
|
2954
|
+
return 0;
|
|
2955
|
+
}
|
|
2956
|
+
throw new UsageError(`unknown subcommand: tax ${sub} (see: steward tax --help)`);
|
|
2957
|
+
}
|
|
2958
|
+
function help(out) {
|
|
2959
|
+
out.out(TAX_USAGE);
|
|
2960
|
+
return 0;
|
|
2961
|
+
}
|
|
2962
|
+
// src/main.ts
|
|
2963
|
+
const CLI_VERSION = "0.11.0";
|
|
2312
2964
|
const USAGE = `steward — Steward CLI (@stewardhq/cli ${CLI_VERSION})
|
|
2313
2965
|
|
|
2314
2966
|
Usage: steward <command> [options]
|
|
@@ -2322,10 +2974,14 @@ Commands:
|
|
|
2322
2974
|
dunning get | set <policy.json> dunning policy (/v1/admin/dunning-policy)
|
|
2323
2975
|
reprice --plan <code> --notice-days <n> move a plan's subscribers to its current price
|
|
2324
2976
|
bank-transfers list | record | fx-report bank transfer reconciliation (/v1/admin/bank-transfers)
|
|
2977
|
+
invoices list | issue invoices not issued yet; write the external invoice number
|
|
2978
|
+
grants list active grants; --subscription none: paying for nothing
|
|
2325
2979
|
credits adjust <ref> <meter> --units=<n> credit entry, negative = adjustment
|
|
2326
2980
|
accounts get | metadata set | unset read an account; set or remove metadata keys
|
|
2327
2981
|
meters get | recompute | close-periods an account's meters; metering repairs (admin)
|
|
2328
2982
|
events send | redeliver send one event; redeliver webhook events (admin)
|
|
2983
|
+
tax thresholds list | set | delete tax registration thresholds and their counters
|
|
2984
|
+
tax sales [--from] [--to] [--csv] paid sales per month and buyer country (admin)
|
|
2329
2985
|
|
|
2330
2986
|
Connection: admin commands use STEWARD_ADMIN_URL + STEWARD_ADMIN_API_KEY; doctor,
|
|
2331
2987
|
accounts, meters and events use STEWARD_URL + STEWARD_API_KEY (or the admin pair). If even
|
|
@@ -2347,7 +3003,10 @@ const COMMANDS = {
|
|
|
2347
3003
|
dunning: dunningCommand,
|
|
2348
3004
|
reprice: repriceCommand,
|
|
2349
3005
|
"bank-transfers": bankTransfersCommand,
|
|
2350
|
-
|
|
3006
|
+
invoices: invoicesCommand,
|
|
3007
|
+
grants: grantsCommand,
|
|
3008
|
+
credits: creditsCommand,
|
|
3009
|
+
tax: taxCommand
|
|
2351
3010
|
};
|
|
2352
3011
|
async function main(argv, ctx) {
|
|
2353
3012
|
const out = createOutput(ctx.stdout, ctx.stderr);
|
|
@@ -2384,8 +3043,7 @@ async function main(argv, ctx) {
|
|
|
2384
3043
|
return 1;
|
|
2385
3044
|
}
|
|
2386
3045
|
}
|
|
2387
|
-
|
|
2388
|
-
//#region src/bin.ts
|
|
3046
|
+
// src/bin.ts
|
|
2389
3047
|
const ctx = {
|
|
2390
3048
|
cwd: process.cwd(),
|
|
2391
3049
|
env: process.env,
|
|
@@ -2416,5 +3074,4 @@ const ctx = {
|
|
|
2416
3074
|
}
|
|
2417
3075
|
};
|
|
2418
3076
|
process.exitCode = await main(process.argv.slice(2), ctx);
|
|
2419
|
-
//#endregion
|
|
2420
3077
|
export {};
|