@wirecat/cli-core 0.606.0 → 0.608.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (209) hide show
  1. package/CHANGELOG.md +196 -0
  2. package/dist/calendar/index.d.ts +1 -0
  3. package/dist/calendar/index.js +1 -0
  4. package/dist/calendar/reads.js +5 -0
  5. package/dist/cli/app-mcp-command.d.ts +6 -2
  6. package/dist/cli/app-mcp-command.js +11 -2
  7. package/dist/cli/csv.d.ts +10 -0
  8. package/dist/cli/csv.js +22 -0
  9. package/dist/cli/early-refusal.d.ts +10 -0
  10. package/dist/cli/early-refusal.js +19 -0
  11. package/dist/cli/index.d.ts +3 -0
  12. package/dist/cli/index.js +3 -0
  13. package/dist/cli/profile-token.d.ts +29 -0
  14. package/dist/cli/profile-token.js +65 -0
  15. package/dist/cli/program.js +4 -2
  16. package/dist/crm/cli/csv.d.ts +23 -0
  17. package/dist/crm/cli/csv.js +135 -0
  18. package/dist/crm/cli/index.d.ts +1 -1
  19. package/dist/crm/cli/index.js +33 -21
  20. package/dist/crm/cli/pipeline-view.d.ts +3 -0
  21. package/dist/crm/cli/pipeline-view.js +36 -0
  22. package/dist/crm/writes.d.ts +6 -4
  23. package/dist/crm/writes.js +17 -13
  24. package/dist/documents.d.ts +2 -0
  25. package/dist/documents.js +2 -0
  26. package/dist/domain/business.d.ts +79 -0
  27. package/dist/domain/business.js +42 -0
  28. package/dist/domain/finance.d.ts +2 -0
  29. package/dist/domain/finance.js +2 -2
  30. package/dist/domain/google-documents.d.ts +2 -0
  31. package/dist/domain/google-documents.js +3 -1
  32. package/dist/domain/money.d.ts +2 -0
  33. package/dist/domain/money.js +11 -3
  34. package/dist/domain/providers.d.ts +36 -1
  35. package/dist/domain/providers.js +69 -7
  36. package/dist/domain/record-fields.d.ts +42 -0
  37. package/dist/domain/record-fields.js +122 -0
  38. package/dist/domain/record-types.d.ts +489 -16
  39. package/dist/domain/record-types.js +374 -7
  40. package/dist/domain/records.d.ts +96 -5
  41. package/dist/domain/records.js +178 -32
  42. package/dist/domain/ref-summaries.js +5 -0
  43. package/dist/domain/references.d.ts +1 -1
  44. package/dist/domain/references.js +5 -0
  45. package/dist/domain/vcard.d.ts +25 -0
  46. package/dist/domain/vcard.js +267 -0
  47. package/dist/entities/deal.d.ts +14 -0
  48. package/dist/entities/deal.js +3 -0
  49. package/dist/entities/index.d.ts +12 -0
  50. package/dist/errors/reasons.js +63 -4
  51. package/dist/fetch/addresses.d.ts +5 -0
  52. package/dist/fetch/addresses.js +76 -0
  53. package/dist/fetch/page.d.ts +64 -0
  54. package/dist/fetch/page.js +256 -0
  55. package/dist/index.d.ts +5 -3
  56. package/dist/index.js +5 -3
  57. package/dist/meetings/calendar-text.d.ts +1 -1
  58. package/dist/meetings/calendar-text.js +4 -0
  59. package/dist/meetings/event-store.d.ts +2 -2
  60. package/dist/search/account-list.d.ts +4 -0
  61. package/dist/search/account-list.js +19 -8
  62. package/dist/search/query.js +2 -2
  63. package/dist/services/events-search.js +2 -2
  64. package/dist/services/index.d.ts +1 -1
  65. package/dist/services/index.js +1 -1
  66. package/dist/services/ingest.d.ts +56 -8
  67. package/dist/services/ingest.js +95 -61
  68. package/dist/services/messages-search.js +3 -2
  69. package/dist/services/metadata.d.ts +1 -1
  70. package/dist/services/notes-search.js +1 -0
  71. package/dist/services/proposals/kinds/contracts.d.ts +4 -0
  72. package/dist/services/proposals/kinds/contracts.js +9 -0
  73. package/dist/services/proposals/kinds/finance.d.ts +4 -0
  74. package/dist/services/proposals/kinds/finance.js +14 -35
  75. package/dist/services/proposals/kinds/orders.js +7 -30
  76. package/dist/services/proposals/kinds/shared.d.ts +27 -1
  77. package/dist/services/proposals/kinds/shared.js +34 -0
  78. package/dist/services/proposals/kinds/source-review.d.ts +4 -0
  79. package/dist/services/proposals/kinds/source-review.js +45 -0
  80. package/dist/services/proposals/kinds/subscriptions.d.ts +9 -0
  81. package/dist/services/proposals/kinds/subscriptions.js +24 -0
  82. package/dist/services/proposals/kinds/transactions.d.ts +4 -0
  83. package/dist/services/proposals/kinds/transactions.js +10 -0
  84. package/dist/services/proposals/registry.js +9 -0
  85. package/dist/services/search-all-meetings.js +2 -2
  86. package/dist/services/search-all.js +4 -3
  87. package/dist/services/search-kind.js +3 -3
  88. package/dist/store/decisions.js +5 -1
  89. package/dist/store/index.d.ts +14 -3
  90. package/dist/store/index.js +3 -0
  91. package/dist/store/people.js +1 -1
  92. package/dist/store/source-review.d.ts +64 -0
  93. package/dist/store/source-review.js +7 -0
  94. package/dist/store/sqlite/accounts.d.ts +1 -1
  95. package/dist/store/sqlite/accounts.js +24 -1
  96. package/dist/store/sqlite/added-sources.d.ts +82 -0
  97. package/dist/store/sqlite/added-sources.js +237 -0
  98. package/dist/store/sqlite/business-contracts.d.ts +90 -0
  99. package/dist/store/sqlite/business-contracts.js +182 -0
  100. package/dist/store/sqlite/calendar-events.js +7 -3
  101. package/dist/store/sqlite/calendar-forget.js +3 -0
  102. package/dist/store/sqlite/calendar.d.ts +21 -1
  103. package/dist/store/sqlite/calendar.js +27 -7
  104. package/dist/store/sqlite/chat-rekey.js +7 -0
  105. package/dist/store/sqlite/chats.d.ts +3 -1
  106. package/dist/store/sqlite/chats.js +15 -1
  107. package/dist/store/sqlite/crm-rows.d.ts +44 -0
  108. package/dist/store/sqlite/crm-rows.js +195 -0
  109. package/dist/store/sqlite/crm.d.ts +2 -11
  110. package/dist/store/sqlite/crm.js +11 -166
  111. package/dist/store/sqlite/deals.d.ts +4 -8
  112. package/dist/store/sqlite/deals.js +5 -3
  113. package/dist/store/sqlite/document-transfer/snapshot.js +2 -2
  114. package/dist/store/sqlite/emails.js +2 -0
  115. package/dist/store/sqlite/entity-types.d.ts +14 -9
  116. package/dist/store/sqlite/entity-types.js +4 -10
  117. package/dist/store/sqlite/evidence-signature.d.ts +114 -0
  118. package/dist/store/sqlite/evidence-signature.js +349 -0
  119. package/dist/store/sqlite/evidence-sources.d.ts +2 -1
  120. package/dist/store/sqlite/evidence-sources.js +7 -3
  121. package/dist/store/sqlite/facts.d.ts +7 -2
  122. package/dist/store/sqlite/facts.js +21 -5
  123. package/dist/store/sqlite/finance.d.ts +18 -105
  124. package/dist/store/sqlite/finance.js +100 -219
  125. package/dist/store/sqlite/knowledge.d.ts +8 -2
  126. package/dist/store/sqlite/knowledge.js +65 -71
  127. package/dist/store/sqlite/labelled.d.ts +3 -0
  128. package/dist/store/sqlite/labelled.js +11 -0
  129. package/dist/store/sqlite/link-kinds.d.ts +2 -0
  130. package/dist/store/sqlite/link-kinds.js +2 -0
  131. package/dist/store/sqlite/manifest.js +2 -0
  132. package/dist/store/sqlite/memories.d.ts +23 -9
  133. package/dist/store/sqlite/memories.js +41 -13
  134. package/dist/store/sqlite/messages.js +2 -0
  135. package/dist/store/sqlite/migrations.generated.js +103 -0
  136. package/dist/store/sqlite/money-lines.d.ts +48 -0
  137. package/dist/store/sqlite/money-lines.js +76 -0
  138. package/dist/store/sqlite/money-transactions.d.ts +132 -0
  139. package/dist/store/sqlite/money-transactions.js +295 -0
  140. package/dist/store/sqlite/notes.d.ts +11 -2
  141. package/dist/store/sqlite/notes.js +20 -25
  142. package/dist/store/sqlite/orders.d.ts +36 -6
  143. package/dist/store/sqlite/orders.js +126 -46
  144. package/dist/store/sqlite/payment-facts.js +1 -1
  145. package/dist/store/sqlite/private-people.js +2 -0
  146. package/dist/store/sqlite/products.d.ts +78 -0
  147. package/dist/store/sqlite/products.js +131 -0
  148. package/dist/store/sqlite/project-transfer/records.js +26 -1
  149. package/dist/store/sqlite/project-transfer/snapshot.js +5 -3
  150. package/dist/store/sqlite/proposed-actions.d.ts +1 -1
  151. package/dist/store/sqlite/proposed-actions.js +24 -7
  152. package/dist/store/sqlite/providers.d.ts +0 -4
  153. package/dist/store/sqlite/providers.js +20 -2
  154. package/dist/store/sqlite/record-matching.d.ts +80 -0
  155. package/dist/store/sqlite/record-matching.js +264 -0
  156. package/dist/store/sqlite/record-projection.d.ts +89 -0
  157. package/dist/store/sqlite/record-projection.js +50 -0
  158. package/dist/store/sqlite/record-projectors-direct.d.ts +17 -0
  159. package/dist/store/sqlite/record-projectors-direct.js +125 -0
  160. package/dist/store/sqlite/record-projectors-money.d.ts +26 -0
  161. package/dist/store/sqlite/record-projectors-money.js +214 -0
  162. package/dist/store/sqlite/record-projectors-phone.d.ts +28 -0
  163. package/dist/store/sqlite/record-projectors-phone.js +212 -0
  164. package/dist/store/sqlite/record-projectors.d.ts +3 -44
  165. package/dist/store/sqlite/record-projectors.js +7 -67
  166. package/dist/store/sqlite/record-relations.d.ts +24 -0
  167. package/dist/store/sqlite/record-relations.js +92 -0
  168. package/dist/store/sqlite/record-remap.d.ts +12 -0
  169. package/dist/store/sqlite/record-remap.js +92 -0
  170. package/dist/store/sqlite/record-run.d.ts +71 -0
  171. package/dist/store/sqlite/record-run.js +179 -0
  172. package/dist/store/sqlite/record-settling.d.ts +9 -0
  173. package/dist/store/sqlite/record-settling.js +74 -0
  174. package/dist/store/sqlite/record-stamps.d.ts +13 -0
  175. package/dist/store/sqlite/record-stamps.js +30 -0
  176. package/dist/store/sqlite/record-writes.d.ts +43 -0
  177. package/dist/store/sqlite/record-writes.js +307 -0
  178. package/dist/store/sqlite/records.d.ts +52 -42
  179. package/dist/store/sqlite/records.js +123 -353
  180. package/dist/store/sqlite/ref-summaries.d.ts +6 -5
  181. package/dist/store/sqlite/ref-summaries.js +60 -8
  182. package/dist/store/sqlite/refunds.d.ts +31 -0
  183. package/dist/store/sqlite/refunds.js +112 -0
  184. package/dist/store/sqlite/reviewed.d.ts +109 -0
  185. package/dist/store/sqlite/reviewed.js +173 -0
  186. package/dist/store/sqlite/schema.d.ts +2840 -83
  187. package/dist/store/sqlite/schema.js +256 -1
  188. package/dist/store/sqlite/source-review-marks.d.ts +54 -0
  189. package/dist/store/sqlite/source-review-marks.js +143 -0
  190. package/dist/store/sqlite/source-review.d.ts +54 -0
  191. package/dist/store/sqlite/source-review.js +221 -0
  192. package/dist/store/sqlite/stage-amounts.d.ts +14 -0
  193. package/dist/store/sqlite/stage-amounts.js +23 -0
  194. package/dist/store/sqlite/subscriptions.d.ts +135 -0
  195. package/dist/store/sqlite/subscriptions.js +294 -0
  196. package/dist/store/sqlite/text-input.d.ts +3 -0
  197. package/dist/store/sqlite/text-input.js +13 -0
  198. package/dist/store/sqlite/things.js +2 -9
  199. package/dist/store/sqlite/transaction.d.ts +15 -0
  200. package/dist/store/sqlite/transaction.js +57 -0
  201. package/dist/store/sqlite/wallets.d.ts +88 -0
  202. package/dist/store/sqlite/wallets.js +143 -0
  203. package/dist/store/store-errors.d.ts +1 -0
  204. package/dist/store/store-errors.js +45 -0
  205. package/dist/store/store.d.ts +16 -1
  206. package/dist/store/store.js +30 -6
  207. package/package.json +5 -2
  208. package/schemas/examples/records-business.jsonl +11 -0
  209. package/schemas/records-envelope.v1.schema.json +1160 -5
@@ -0,0 +1,135 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { annotateOption } from "@wirecat/cli-base/commands";
3
+ import { Option } from "commander";
4
+ import { compactOf, environmentOf, inCommandRun, outputFor } from "../../cli/context.js";
5
+ import { writeCsv } from "../../cli/csv.js";
6
+ import { fieldsOf } from "../../cli/result-fields.js";
7
+ /**
8
+ * `--format csv`: `--format` is the vocabulary's output choice, so no CLI's command lint needs a new word. Off MCP: a
9
+ * table carries no `untrusted` marker for an agent.
10
+ */
11
+ export const csvFormatOption = () => annotateOption(new Option("--format <format>", "csv: this page as a table for a spreadsheet; --json=a,b picks its columns").choices(["csv"]), { mcp: false });
12
+ const DEFAULT_COLUMNS = [
13
+ "ref",
14
+ "title",
15
+ "status",
16
+ "pipeline",
17
+ "pipeline_name",
18
+ "stage",
19
+ "amount",
20
+ "currency",
21
+ "organization",
22
+ "people",
23
+ "close_date",
24
+ "closed_date",
25
+ "closed_reason",
26
+ "assignee",
27
+ "external_id",
28
+ "created_at",
29
+ "updated_at",
30
+ "provider_metadata",
31
+ ];
32
+ const isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
33
+ const at = (item, path) => path.reduce((value, key) => (isRecord(value) ? value[key] : undefined), item);
34
+ /** One cell's text: a party by its name, a list joined, so no cell holds JSON a spreadsheet cannot read. */
35
+ const flat = (value) => {
36
+ if (Array.isArray(value))
37
+ return value.map(flat).join("; ");
38
+ if (isRecord(value))
39
+ return value.name ?? value.ref ?? JSON.stringify(value);
40
+ return value;
41
+ };
42
+ const MONEY = /^(-?\d+(?:\.\d+)?)\|([A-Za-z]{3})$/;
43
+ /** A CRM's own field: headed by its label as `fields list` shows it; money as an amount and a currency column. */
44
+ const customColumns = (field, header) => {
45
+ const value = (item) => at(item, ["provider_metadata", field.code, "value"]);
46
+ if (field.type !== "money")
47
+ return [{ header, cell: (item) => flat(value(item)) }];
48
+ const part = (index) => (item) => {
49
+ const raw = value(item);
50
+ const money = typeof raw === "string" ? MONEY.exec(raw) : null;
51
+ return money ? money[index] : index === 1 ? flat(raw) : null;
52
+ };
53
+ return [
54
+ { header: `${header} amount`, cell: part(1) },
55
+ { header: `${header} currency`, cell: part(2) },
56
+ ];
57
+ };
58
+ /** Every custom field the CRM lists, then any a row holds that the list does not, each header told apart by code. */
59
+ const customFieldsOf = (page) => {
60
+ const listed = new Set(page.fields.map((field) => field.code));
61
+ const extra = new Map();
62
+ for (const item of page.items) {
63
+ const metadata = item.provider_metadata;
64
+ if (!isRecord(metadata))
65
+ continue;
66
+ for (const [code, value] of Object.entries(metadata))
67
+ if (!listed.has(code) && !extra.has(code)) {
68
+ const label = isRecord(value) && typeof value.label === "string" ? value.label : null;
69
+ extra.set(code, { code, label, type: "string", multiple: false, filterable: false });
70
+ }
71
+ }
72
+ return [...page.fields, ...extra.values()];
73
+ };
74
+ const columnsOf = (page, paths) => {
75
+ const custom = customFieldsOf(page);
76
+ const taken = new Set(paths.filter((path) => !path.startsWith("provider_metadata")));
77
+ const labels = new Map();
78
+ for (const field of custom)
79
+ labels.set(field.label ?? field.code, (labels.get(field.label ?? field.code) ?? 0) + 1);
80
+ const headerOf = (field) => {
81
+ const label = field.label ?? field.code;
82
+ return (labels.get(label) ?? 0) > 1 || taken.has(label) ? `${label} (${field.code})` : label;
83
+ };
84
+ return paths.flatMap((path) => {
85
+ const parts = path.split(".");
86
+ if (parts[0] !== "provider_metadata")
87
+ return [{ header: path, cell: (item) => flat(at(item, parts)) }];
88
+ const chosen = parts[1] === undefined ? custom : custom.filter((field) => field.code === parts[1]);
89
+ return chosen.flatMap((field) => customColumns(field, headerOf(field)));
90
+ });
91
+ };
92
+ /** `--json=a,b` beside `--format csv` names its columns, `items.` or not, as `--json` would keep them. */
93
+ const pathsOf = (command) => {
94
+ const fields = command.optsWithGlobals().fields;
95
+ if (fields === undefined)
96
+ return DEFAULT_COLUMNS;
97
+ return fieldsOf(fields).map((path) => (path.startsWith("items.") ? path.slice("items.".length) : path));
98
+ };
99
+ const refuse = (message) => {
100
+ throw new CliError("validation_error", message, { reason: "output.conflict", param: "--format" });
101
+ };
102
+ /** A table is for a person's spreadsheet: JSON, JSON lines, compact rows and an agent's run each ask for another. */
103
+ const refuseOtherOutput = (command) => {
104
+ const globals = command.optsWithGlobals();
105
+ if (environmentOf(command).agent)
106
+ refuse("--format csv is a table for a spreadsheet; an agent reads the JSON answer");
107
+ if (globals.jsonl)
108
+ refuse("--format csv and --jsonl ask for different output — pick one");
109
+ if (compactOf(command))
110
+ refuse("--format csv and --compact ask for different output — pick one");
111
+ if (globals.json && globals.fields === undefined)
112
+ refuse("--format csv and --json ask for different output — --json=a,b picks the table's columns");
113
+ };
114
+ /**
115
+ * Reads a page in the profile's run, closes it, then prints the table: stdout carries the CSV and nothing else, and
116
+ * the way to the next page goes to stderr.
117
+ */
118
+ export const renderCsv = (command, open, read) => {
119
+ refuseOtherOutput(command);
120
+ return inCommandRun(command, async () => {
121
+ const run = await open(command, { readOnly: true });
122
+ let page;
123
+ try {
124
+ page = await read(run);
125
+ }
126
+ finally {
127
+ await run.close?.();
128
+ }
129
+ const columns = columnsOf(page, pathsOf(command));
130
+ const { streams, renderer } = outputFor(command);
131
+ writeCsv(streams, columns.map((column) => column.header), page.items.map((item) => columns.map((column) => column.cell(item))));
132
+ if (page.hasMore)
133
+ renderer.note(`→ more rows: run it again with --page ${page.page + 1}`);
134
+ });
135
+ };
@@ -59,5 +59,5 @@ export declare const STAGES_QUERY: {
59
59
  readonly backend: "native";
60
60
  readonly fields: readonly [import("@wirecat/cli-base/query").FieldSpec, import("@wirecat/cli-base/query").FieldSpec];
61
61
  };
62
- export type CrmWithin = (command: Command, work: (run: CrmRun) => Promise<Body>) => Promise<void>;
62
+ export type CrmWithin = (command: Command, work: (run: CrmRun) => Promise<Body>, view?: (body: Body) => string) => Promise<void>;
63
63
  export declare const addCrmCommands: (program: Command, options: CrmCommandOptions) => void;
@@ -15,7 +15,9 @@ import { DEAL_KINDS, DEAL_STATUSES } from "../../domain/deals.js";
15
15
  import { deal as dealEntity } from "../../entities/deal.js";
16
16
  import { count, text } from "../../entities/fields.js";
17
17
  import { crmStatus, syncCrm } from "../sync.js";
18
- import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, removeCrmItem, updateCrmItem, } from "../writes.js";
18
+ import { closeCrmItem, createCrmItem, fieldPairsOf, moveCrmItem, pipelineOf, removeCrmItem, updateCrmItem, } from "../writes.js";
19
+ import { csvFormatOption, renderCsv } from "./csv.js";
20
+ import { pipelineView } from "./pipeline-view.js";
19
21
  import { addCrmSearchAll } from "./search-all.js";
20
22
  const MOST = 500;
21
23
  const DEAL_FIELDS = [
@@ -139,7 +141,7 @@ const dealKeys = snakeKeysKeeping(["providerMetadata"]);
139
141
  const marked = (items, untrusted) => items.map((item) => ({ ...dealKeys(item), untrusted }));
140
142
  const addCrmCommandsDefinition = (program, options) => {
141
143
  const now = () => options.now?.() ?? Date.now();
142
- const within = (command, work) => inCommandRun(command, async () => {
144
+ const within = (command, work, view) => inCommandRun(command, async () => {
143
145
  const run = await options.open(command, { readOnly: metaOf(command).effects?.local !== "write" });
144
146
  let body;
145
147
  try {
@@ -148,7 +150,7 @@ const addCrmCommandsDefinition = (program, options) => {
148
150
  finally {
149
151
  await run.close?.();
150
152
  }
151
- renderAnswer(command, outputFor(command), body);
153
+ renderAnswer(command, outputFor(command), body, view);
152
154
  });
153
155
  const example = (command, ...lines) => annotate(command, { examples: lines.map((line) => `${options.app.command} work ${line}`) });
154
156
  example(answerEntity(annotate(program.command("sync"), { effects: FETCH, offline: false, cooperative: true, partial: true }), "crm_sync", crmSync).description("bring the CRM's copy in the local store up to date: pipelines, companies, contacts, deals and leads that " +
@@ -232,22 +234,31 @@ const addCrmCommandsDefinition = (program, options) => {
232
234
  : "the CRM's leads as last synced");
233
235
  example(withQuery(annotate(group.command("list"), { effects: LOCAL_READ, output: { entity: kind } }).description(`${plural} copied from the CRM, newest first; run sync to bring them up to date`), query)
234
236
  .option("--limit <n>", `${plural} per page, 1–${MOST}`, integer(MOST), 50)
235
- .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1), `${plural} list status:open --json`, `${plural} list stage:"Quote sent"`).action(async (words, opts, command) => {
237
+ .option("--page <n>", "which page, starting at 1", integer(1_000_000), 1)
238
+ .addOption(csvFormatOption()), `${plural} list status:open --json`, `${plural} list stage:"Quote sent"`, `${plural} list status:open --format csv > ${plural}.csv`).action(async (words, opts, command) => {
236
239
  const terms = queryTerms(words, query, `${plural} list`);
237
- await within(command, async (run) => {
238
- const filter = {
239
- kind,
240
- account: run.account,
241
- ...(terms.has("status") ? { status: terms.get("status") } : {}),
242
- ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
243
- ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
244
- ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
245
- };
246
- const found = await run.store.deals.list({
247
- ...filter,
248
- limit: Math.min(opts.limit + 1, MOST),
249
- offset: (opts.page - 1) * opts.limit,
240
+ const read = (run) => run.store.deals.list({
241
+ kind,
242
+ account: run.account,
243
+ ...(terms.has("status") ? { status: terms.get("status") } : {}),
244
+ ...(terms.has("stage") ? { stage: terms.get("stage") } : {}),
245
+ ...(terms.has("pipeline") ? { pipeline: terms.get("pipeline") } : {}),
246
+ ...(terms.has("organization") ? { organization: terms.get("organization") } : {}),
247
+ limit: Math.min(opts.limit + 1, MOST),
248
+ offset: (opts.page - 1) * opts.limit,
249
+ });
250
+ if (opts.format === "csv")
251
+ return renderCsv(command, options.open, async (run) => {
252
+ const found = await read(run);
253
+ return {
254
+ items: marked(found.slice(0, opts.limit), DEAL_UNTRUSTED),
255
+ fields: await run.store.crm.fields(run.account, kind),
256
+ page: opts.page,
257
+ hasMore: found.length > opts.limit,
258
+ };
250
259
  });
260
+ await within(command, async (run) => {
261
+ const found = await read(run);
251
262
  return listOf(pathOf(command).join(" "), {
252
263
  items: marked(found.slice(0, opts.limit), DEAL_UNTRUSTED),
253
264
  limit: opts.limit,
@@ -395,12 +406,13 @@ const addCrmCommandsDefinition = (program, options) => {
395
406
  });
396
407
  });
397
408
  example(annotate(pipelines.command("show"), { effects: LOCAL_READ, output: { entity: "pipeline" } })
398
- .description("one pipeline with its funnel: how many reached each stage, how many went on, and the win rate")
399
- .argument("<pipeline>", "pipeline:<id>, or a name only one of the CRM's pipelines has"), "pipelines show pipeline:3").action(async (reference, _opts, command) => {
409
+ .description("one pipeline as a board and a funnel: how many stand in each stage and their sum per currency, never " +
410
+ "converted, how many reached it and went on, and the win rate; won and lost stages are marked by outcome")
411
+ .argument("[pipeline]", "pipeline:<id>, or a name only one of the CRM's pipelines has; needed unless the CRM has one pipeline in all"), "pipelines show pipeline:3", "pipelines show Sales --json").action(async (reference, _opts, command) => {
400
412
  await within(command, async (run) => {
401
- const report = await run.store.deals.pipeline(reference, { account: run.account });
413
+ const report = await pipelineOf(run, undefined, reference, "pipeline");
402
414
  return itemOf({ ...snakeKeys(report), untrusted: PIPELINE_UNTRUSTED });
403
- });
415
+ }, (body) => pipelineView(body, outputFor(command).color));
404
416
  });
405
417
  const stages = annotate(program.command("stages"), { effects: NO_EFFECTS }).description("the stages of the CRM's pipelines, as last synced");
406
418
  example(withQuery(annotate(stages.command("list"), { effects: LOCAL_READ, output: { entity: "stage" } }).description("every stage of the CRM's pipelines in order, with its outcome and how many are open in it"), STAGES_QUERY), "stages list --json", "stages list kind:lead").action(async (words, _opts, command) => {
@@ -0,0 +1,3 @@
1
+ import type { Body } from "../../cli/envelope.js";
2
+ /** `pipelines show` at a terminal: the board as a table, then what the open stages hold and how the closed ended. */
3
+ export declare const pipelineView: (body: Body, color: boolean) => string;
@@ -0,0 +1,36 @@
1
+ import { renderPretty } from "@wirecat/cli-base";
2
+ import { formatDecimal, groupDigits, parseDecimal, scaleOf } from "../../domain/money.js";
3
+ const sumOf = (amounts) => amounts.map(({ amount, currency }) => `${groupDigits(amount)} ${currency}`).join(", ") || "—";
4
+ const percent = (share) => (share === null ? "—" : `${Math.round(share * 100)}%`);
5
+ const openStages = (stages) => {
6
+ const sums = new Map();
7
+ let items = 0;
8
+ for (const stage of stages.filter((one) => one.outcome === "open")) {
9
+ items += stage.items;
10
+ for (const { amount, currency } of stage.amounts)
11
+ sums.set(currency, (sums.get(currency) ?? 0n) + (parseDecimal(amount, scaleOf(currency)) ?? 0n));
12
+ }
13
+ const amounts = [...sums].map(([currency, units]) => ({
14
+ amount: formatDecimal(units, scaleOf(currency)),
15
+ currency,
16
+ }));
17
+ return `in open stages: ${items} · ${sumOf(amounts)}`;
18
+ };
19
+ /** `pipelines show` at a terminal: the board as a table, then what the open stages hold and how the closed ended. */
20
+ export const pipelineView = (body, color) => {
21
+ const pipeline = body.item;
22
+ const rows = pipeline.stages.map((stage) => ({
23
+ stage: stage.name,
24
+ outcome: stage.outcome,
25
+ [`${pipeline.kind}s`]: stage.items,
26
+ sum: sumOf(stage.amounts),
27
+ reached: stage.reached,
28
+ "went on": percent(stage.conversion),
29
+ }));
30
+ const { won, lost, win_rate } = pipeline.totals;
31
+ return [
32
+ `${pipeline.name} (${pipeline.ref})`,
33
+ renderPretty(rows, { color }),
34
+ `${openStages(pipeline.stages)}\nwon: ${won} · lost: ${lost} · win rate ${percent(win_rate)}`,
35
+ ].join("\n\n");
36
+ };
@@ -5,7 +5,7 @@ import type { AppIdentity } from "../ports/app.js";
5
5
  import type { Warn } from "../runs/events.js";
6
6
  import { type Asker, type GuardSettings } from "../sends/guard.js";
7
7
  import { type PermissionKey } from "../sends/permissions.js";
8
- import type { Deal } from "../store/sqlite/deals.js";
8
+ import type { Deal, PipelineReport } from "../store/sqlite/deals.js";
9
9
  import type { MessageStore } from "../store/store.js";
10
10
  import type { AccountKey } from "../store/types.js";
11
11
  import type { CrmSource } from "./source.js";
@@ -54,6 +54,8 @@ export interface CrmFieldsInput {
54
54
  */
55
55
  custom?: readonly (readonly [name: string, value: string])[];
56
56
  }
57
+ /** The named pipeline of this profile's CRM account, or its only one; several and none named is refused. */
58
+ export declare const pipelineOf: (context: Pick<CrmWriteContext, "store" | "account">, kind: DealKind | undefined, reference: string | undefined, param?: string) => Promise<PipelineReport>;
57
59
  /** What the field lookup reads of a field definition: a CRM CLI's own type fits. */
58
60
  export type NamedField = Pick<CrmField, "code" | "label" | "options">;
59
61
  /**
@@ -62,11 +64,11 @@ export type NamedField = Pick<CrmField, "code" | "label" | "options">;
62
64
  */
63
65
  export declare const foldFieldName: (name: string) => string;
64
66
  /** No field by that name: the fields whose code or label holds it, or is held in it, are its candidates. */
65
- export declare const unknownField: (fields: readonly NamedField[], name: string) => CliError;
67
+ export declare const unknownField: (fields: readonly NamedField[], name: string, param?: string) => CliError;
66
68
  /** A field by its code or its whole label; two with that label are refused with both, never guessed. */
67
- export declare const fieldNamed: <F extends NamedField>(fields: readonly F[], name: string) => F;
69
+ export declare const fieldNamed: <F extends NamedField>(fields: readonly F[], name: string, param?: string) => F;
68
70
  /** A list field's option id, by its id or its whole label; a field with no options takes the value as typed. */
69
- export declare const optionOf: (field: NamedField, value: string) => string;
71
+ export declare const optionOf: (field: NamedField, value: string, param?: string) => string;
70
72
  /** `--field` pairs as typed, split at the first `=`; a pair with no key before it is refused. */
71
73
  export declare const fieldPairsOf: (typed: readonly string[]) => [string, string][];
72
74
  export interface CrmWritten {
@@ -55,19 +55,23 @@ const copyOf = async (context, kind, reference) => {
55
55
  throw new CliError("not_found", `${reference} is not a copy from this profile's CRM account`);
56
56
  return found;
57
57
  };
58
- const pipelineOf = async (context, kind, reference) => {
58
+ /** The named pipeline of this profile's CRM account, or its only one; several and none named is refused. */
59
+ export const pipelineOf = async (context, kind, reference, param = "--pipeline") => {
60
+ const scope = { ...(kind ? { kind } : {}), account: context.account };
59
61
  if (reference !== undefined) {
60
- const found = await context.store.deals.pipeline(reference, { kind, account: context.account });
62
+ const found = await context.store.deals.pipeline(reference, scope);
61
63
  if (found.externalId === null)
62
64
  throw new CliError("not_found", `${reference} is not a pipeline of this CRM account`);
63
65
  return found;
64
66
  }
65
- const all = await context.store.deals.pipelines({ kind, account: context.account });
67
+ const all = await context.store.deals.pipelines(scope);
66
68
  if (all.length === 1)
67
- return all[0];
69
+ return context.store.deals.pipeline(all[0].ref, scope);
70
+ const what = kind ? `${kind} pipeline` : "pipeline";
68
71
  throw new CliError("validation_error", all.length === 0
69
- ? `no ${kind} pipeline of this CRM is stored; run sync first`
70
- : `this CRM has ${all.length} ${kind} pipelines; name one with --pipeline: ${all.map(({ name }) => name).join(", ")}`, { reason: "crm.pipeline-required", param: "--pipeline" });
72
+ ? `no ${what} of this CRM is stored; run sync first`
73
+ : `this CRM has ${all.length} ${what}s; name one${param.startsWith("--") ? ` with ${param}` : ""}: ` +
74
+ all.map(({ name, ref }) => `${name} (${ref})`).join(", "), { reason: "crm.pipeline-required", param, allowed: all.map(({ ref }) => ref) });
71
75
  };
72
76
  /** A stage of `pipeline`, by the CRM's id or by a name only one of its stages has, in any letter case. */
73
77
  const stageOf = (pipeline, given) => {
@@ -128,16 +132,16 @@ const fieldsOf = (input, pipeline, currency) => {
128
132
  export const foldFieldName = (name) => foldName(name.trim()).replace(/[\s_]+/gu, " ");
129
133
  const named = ({ code, label }) => ({ code, label });
130
134
  /** No field by that name: the fields whose code or label holds it, or is held in it, are its candidates. */
131
- export const unknownField = (fields, name) => {
135
+ export const unknownField = (fields, name, param = "--field") => {
132
136
  const want = foldFieldName(name);
133
137
  const close = fields.filter((field) => [field.code, field.label ?? ""].some((one) => {
134
138
  const other = foldFieldName(one);
135
139
  return other !== "" && (other.includes(want) || want.includes(other));
136
140
  }));
137
- return new CliError("validation_error", `no custom field is named ${name}${close.length ? "; close ones are in candidates" : ""} — \`fields list\` lists them`, { reason: "field.unknown", param: "--field", candidates: close.map(named) });
141
+ return new CliError("validation_error", `no custom field is named ${name}${close.length ? "; close ones are in candidates" : ""} — \`fields list\` lists them`, { reason: "field.unknown", param, candidates: close.map(named) });
138
142
  };
139
143
  /** A field by its code or its whole label; two with that label are refused with both, never guessed. */
140
- export const fieldNamed = (fields, name) => {
144
+ export const fieldNamed = (fields, name, param = "--field") => {
141
145
  const want = foldFieldName(name);
142
146
  const byCode = fields.find((field) => foldFieldName(field.code) === want);
143
147
  if (byCode)
@@ -148,13 +152,13 @@ export const fieldNamed = (fields, name) => {
148
152
  if (labelled.length > 1)
149
153
  throw new CliError("validation_error", `${labelled.length} custom fields are labelled ${name}; name one by its code`, {
150
154
  reason: "field.ambiguous",
151
- param: "--field",
155
+ param,
152
156
  candidates: labelled.map(named),
153
157
  });
154
- throw unknownField(fields, name);
158
+ throw unknownField(fields, name, param);
155
159
  };
156
160
  /** A list field's option id, by its id or its whole label; a field with no options takes the value as typed. */
157
- export const optionOf = (field, value) => {
161
+ export const optionOf = (field, value, param = "--field") => {
158
162
  if (!field.options)
159
163
  return value;
160
164
  const want = foldFieldName(value);
@@ -163,7 +167,7 @@ export const optionOf = (field, value) => {
163
167
  if (!found)
164
168
  throw new CliError("validation_error", `${field.label ?? field.code} has no option ${value}`, {
165
169
  reason: "field.unknown-option",
166
- param: "--field",
170
+ param,
167
171
  field: field.code,
168
172
  allowed: field.options,
169
173
  });
@@ -5,5 +5,7 @@ export { attachmentMaxBytes } from "./attachments/limits.js";
5
5
  export type { Sheet, SheetCell } from "./attachments/sheets.js";
6
6
  export { columnName, sheetText } from "./attachments/sheets.js";
7
7
  export * from "./documents/index.js";
8
+ export { isPublicAddress } from "./fetch/addresses.js";
9
+ export { type FetchedPage, type FetchPageOptions, fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, type PageLimits, type PageLookup, type PageRequest, type PageResponse, type PageTransport, type ResolvedAddress, } from "./fetch/page.js";
8
10
  export { registerReader } from "./readers/registry.js";
9
11
  export type { ReadContext, Reader, Section } from "./readers/types.js";
package/dist/documents.js CHANGED
@@ -3,4 +3,6 @@ export { extractText, importEngine, MAX_FILE_BYTES, MAX_TEXT_CHARS } from "./att
3
3
  export { attachmentMaxBytes } from "./attachments/limits.js";
4
4
  export { columnName, sheetText } from "./attachments/sheets.js";
5
5
  export * from "./documents/index.js";
6
+ export { isPublicAddress } from "./fetch/addresses.js";
7
+ export { fetchPage, nodeTransport, PAGE_LIMITS, PAGE_USER_AGENT, } from "./fetch/page.js";
6
8
  export { registerReader } from "./readers/registry.js";
@@ -0,0 +1,79 @@
1
+ import { type FinanceReview, type MoneyDirection } from "./finance.js";
2
+ export declare const CATALOG_KINDS: readonly ["product", "service"];
3
+ export declare const CONTRACT_KINDS: readonly ["sale", "purchase", "service", "lease", "employment", "nda", "license", "other"];
4
+ export declare const CONTRACT_STATUSES: readonly ["draft", "active", "ended", "terminated"];
5
+ export declare const PERIOD_UNITS: readonly ["day", "week", "month", "year"];
6
+ export declare const SUBSCRIPTION_STATUSES: readonly ["trial", "active", "paused", "cancelled", "ended"];
7
+ export declare const WALLET_KINDS: readonly ["bank", "card", "cash", "wallet", "other"];
8
+ /** Only a booked transaction counts in a balance; a pending one is shown beside it. */
9
+ export declare const TRANSACTION_STATUSES: readonly ["pending", "booked"];
10
+ /** `purchase`: the owner buys, as every order before store version 57; `sale`: the owner sells. */
11
+ export declare const ORDER_DIRECTIONS: readonly ["purchase", "sale"];
12
+ export type CatalogKind = (typeof CATALOG_KINDS)[number];
13
+ export type ContractKind = (typeof CONTRACT_KINDS)[number];
14
+ export type ContractStatus = (typeof CONTRACT_STATUSES)[number];
15
+ export type PeriodUnit = (typeof PERIOD_UNITS)[number];
16
+ export type SubscriptionStatus = (typeof SUBSCRIPTION_STATUSES)[number];
17
+ export type WalletKind = (typeof WALLET_KINDS)[number];
18
+ export type TransactionStatus = (typeof TRANSACTION_STATUSES)[number];
19
+ export type OrderDirection = (typeof ORDER_DIRECTIONS)[number];
20
+ export interface Interval {
21
+ count: number;
22
+ unit: PeriodUnit;
23
+ }
24
+ /** `1-month`, `2-week` or a bare `year`, as `--every` takes it. */
25
+ export declare const intervalOf: (text: unknown, reason?: string) => Interval;
26
+ export declare const intervalText: ({ count, unit }: Interval) => string;
27
+ export interface ProductTitleFields {
28
+ name: string;
29
+ kind: CatalogKind;
30
+ unitPrice: number | null;
31
+ currency: string | null;
32
+ unit: string | null;
33
+ archived: boolean;
34
+ }
35
+ /** "Bike rental, month · 10 000.00 RUB per month (service)". */
36
+ export declare const productLine: (product: ProductTitleFields) => string;
37
+ export interface ContractTitleFields {
38
+ id: number;
39
+ name: string;
40
+ number: string | null;
41
+ value: number | null;
42
+ currency: string | null;
43
+ status: ContractStatus;
44
+ review: FinanceReview;
45
+ }
46
+ /** "K-2026-14 · Rental agreement, 120 000.00 RUB (active)". */
47
+ export declare const contractLine: (contract: ContractTitleFields) => string;
48
+ export interface SubscriptionTitleFields {
49
+ name: string;
50
+ interval: Interval;
51
+ /** The current price, when one is confirmed. */
52
+ price: number | null;
53
+ currency: string | null;
54
+ status: SubscriptionStatus;
55
+ review: FinanceReview;
56
+ }
57
+ /** "Hosting, 990.00 RUB every 1-month (active, proposed)". */
58
+ export declare const subscriptionLine: (subscription: SubscriptionTitleFields) => string;
59
+ export interface WalletTitleFields {
60
+ name: string;
61
+ kind: WalletKind;
62
+ currency: string;
63
+ numberHint: string | null;
64
+ closed: boolean;
65
+ }
66
+ /** "Tinkoff · bank, RUB, …1234 (closed)". */
67
+ export declare const walletLine: (wallet: WalletTitleFields) => string;
68
+ export interface TransactionTitleFields {
69
+ direction: MoneyDirection;
70
+ amount: number;
71
+ currency: string;
72
+ /** As the statement names the other side, or else its description. */
73
+ label: string | null;
74
+ date: string;
75
+ status: TransactionStatus;
76
+ review: FinanceReview;
77
+ }
78
+ /** "500.00 RUB out · Кофейня, 14.11 (pending, proposed)". */
79
+ export declare const transactionLine: (transaction: TransactionTitleFields) => string;
@@ -0,0 +1,42 @@
1
+ import { CliError } from "@wirecat/cli-base";
2
+ import { dayMonth, notes } from "./finance.js";
3
+ import { moneyLabel } from "./money.js";
4
+ export const CATALOG_KINDS = ["product", "service"];
5
+ export const CONTRACT_KINDS = ["sale", "purchase", "service", "lease", "employment", "nda", "license", "other"];
6
+ export const CONTRACT_STATUSES = ["draft", "active", "ended", "terminated"];
7
+ export const PERIOD_UNITS = ["day", "week", "month", "year"];
8
+ export const SUBSCRIPTION_STATUSES = ["trial", "active", "paused", "cancelled", "ended"];
9
+ export const WALLET_KINDS = ["bank", "card", "cash", "wallet", "other"];
10
+ /** Only a booked transaction counts in a balance; a pending one is shown beside it. */
11
+ export const TRANSACTION_STATUSES = ["pending", "booked"];
12
+ /** `purchase`: the owner buys, as every order before store version 57; `sale`: the owner sells. */
13
+ export const ORDER_DIRECTIONS = ["purchase", "sale"];
14
+ /** `1-month`, `2-week` or a bare `year`, as `--every` takes it. */
15
+ export const intervalOf = (text, reason = "subscription.interval") => {
16
+ const match = typeof text === "string" ? /^(?:([1-9]\d{0,2})-)?(day|week|month|year)$/.exec(text.trim()) : null;
17
+ if (!match)
18
+ throw new CliError("validation_error", "an interval is a count and a unit, such as 1-month or 2-week", { reason });
19
+ return { count: match[1] === undefined ? 1 : Number(match[1]), unit: match[2] };
20
+ };
21
+ export const intervalText = ({ count, unit }) => `${count}-${unit}`;
22
+ const priced = (units, currency) => units === null || currency === null ? "" : `, ${moneyLabel(units, currency)}`;
23
+ const pending = (review) => (review === "confirmed" ? null : review);
24
+ /** "Bike rental, month · 10 000.00 RUB per month (service)". */
25
+ export const productLine = (product) => {
26
+ const price = product.unitPrice === null || product.currency === null ? "" : moneyLabel(product.unitPrice, product.currency);
27
+ const per = price && product.unit !== null ? ` per ${product.unit}` : "";
28
+ return `${product.name}${price ? ` · ${price}${per}` : ""}${notes(product.kind, product.archived ? "archived" : null)}`;
29
+ };
30
+ /** "K-2026-14 · Rental agreement, 120 000.00 RUB (active)". */
31
+ export const contractLine = (contract) => `${contract.number ?? `#${contract.id}`} · ${contract.name}${priced(contract.value, contract.currency)}` +
32
+ notes(contract.status, pending(contract.review));
33
+ /** "Hosting, 990.00 RUB every 1-month (active, proposed)". */
34
+ export const subscriptionLine = (subscription) => `${subscription.name}${priced(subscription.price, subscription.currency)} every ${intervalText(subscription.interval)}` +
35
+ notes(subscription.status, pending(subscription.review));
36
+ /** "Tinkoff · bank, RUB, …1234 (closed)". */
37
+ export const walletLine = (wallet) => `${wallet.name} · ${wallet.kind}, ${wallet.currency}${wallet.numberHint === null ? "" : `, …${wallet.numberHint}`}` +
38
+ notes(wallet.closed ? "closed" : null);
39
+ /** "500.00 RUB out · Кофейня, 14.11 (pending, proposed)". */
40
+ export const transactionLine = (transaction) => `${moneyLabel(transaction.amount, transaction.currency)} ${transaction.direction}` +
41
+ `${transaction.label === null ? "" : ` · ${transaction.label}`}, ${dayMonth(transaction.date)}` +
42
+ notes(transaction.status === "pending" ? "pending" : null, pending(transaction.review));
@@ -10,6 +10,8 @@ export type MoneyDirection = (typeof MONEY_DIRECTIONS)[number];
10
10
  export type FinanceReview = (typeof FINANCE_REVIEWS)[number];
11
11
  /** An invoice's status from what confirmed payments settle; `draft` and `void` are the owner's and stay. */
12
12
  export declare const settledStatus: (current: InvoiceStatus, total: number, paid: number) => InvoiceStatus;
13
+ export declare const dayMonth: (date: string | null) => string | null;
14
+ export declare const notes: (...words: (string | null)[]) => string;
13
15
  export interface InvoiceTitleFields {
14
16
  id: number;
15
17
  number: string | null;
@@ -13,8 +13,8 @@ export const settledStatus = (current, total, paid) => {
13
13
  return "issued";
14
14
  return paid < total ? "partly_paid" : "paid";
15
15
  };
16
- const dayMonth = (date) => (date === null ? null : `${date.slice(8, 10)}.${date.slice(5, 7)}`);
17
- const notes = (...words) => {
16
+ export const dayMonth = (date) => (date === null ? null : `${date.slice(8, 10)}.${date.slice(5, 7)}`);
17
+ export const notes = (...words) => {
18
18
  const kept = words.filter((word) => word !== null);
19
19
  return kept.length === 0 ? "" : ` (${kept.join(", ")})`;
20
20
  };
@@ -6,6 +6,8 @@ export interface GoogleDocumentLink {
6
6
  }
7
7
  /** A URL as written, without the sentence's punctuation after it; closing brackets stay when the URL opened them. */
8
8
  export declare const trimUrl: (url: string) => string;
9
+ /** Whether the host serves Google Docs, Sheets, Slides or Drive files. */
10
+ export declare const isGoogleDocumentHost: (hostname: string) => boolean;
9
11
  /** The Google file id a Docs, Sheets, Slides, Forms or Drive URL carries; `null` for any other URL. */
10
12
  export declare const googleDocumentId: (url: string) => string | null;
11
13
  /** Every Google document link in the text, in order; the reader and drive's link writer both use it. */
@@ -21,6 +21,8 @@ export const trimUrl = (url) => {
21
21
  }
22
22
  return url.slice(0, end);
23
23
  };
24
+ /** Whether the host serves Google Docs, Sheets, Slides or Drive files. */
25
+ export const isGoogleDocumentHost = (hostname) => /^(?:docs|drive|sheets|slides)\.google\.com$/.test(hostname.toLowerCase());
24
26
  /** The Google file id a Docs, Sheets, Slides, Forms or Drive URL carries; `null` for any other URL. */
25
27
  export const googleDocumentId = (url) => {
26
28
  let parsed;
@@ -30,7 +32,7 @@ export const googleDocumentId = (url) => {
30
32
  catch {
31
33
  return null;
32
34
  }
33
- if (!/^(?:docs|drive|sheets|slides)\.google\.com$/.test(parsed.hostname.toLowerCase()))
35
+ if (!isGoogleDocumentHost(parsed.hostname))
34
36
  return null;
35
37
  const segments = parsed.pathname.split("/");
36
38
  const at = segments.indexOf("d");
@@ -17,6 +17,8 @@ export declare const currencyOf: (text: unknown) => string;
17
17
  export declare const scaleOf: (currency: string) => number;
18
18
  /** Minor units of `currency` for a decimal string such as "50000.00"; refuses more decimals than the currency has. */
19
19
  export declare const minorUnits: (amount: unknown, currency: string, what?: string) => number;
20
+ /** Minor units for a decimal that may be negative, such as an opening balance of "-1200.50". */
21
+ export declare const signedMinorUnits: (amount: unknown, currency: string, what?: string) => number;
20
22
  export declare const moneyOf: (units: number, currency: string) => Money;
21
23
  /** "50 000.00 RUB". */
22
24
  export declare const moneyLabel: (units: number, currency: string) => string;
@@ -51,9 +51,10 @@ export const parseDecimal = (text, scale) => {
51
51
  return BigInt(`${match[1]}${(match[2] ?? "").padEnd(scale, "0")}`);
52
52
  };
53
53
  export const formatDecimal = (units, scale) => {
54
- const digits = BigInt(units)
55
- .toString()
56
- .padStart(scale + 1, "0");
54
+ const value = BigInt(units);
55
+ if (value < 0n)
56
+ return `-${formatDecimal(-value, scale)}`;
57
+ const digits = value.toString().padStart(scale + 1, "0");
57
58
  return scale === 0 ? digits : `${digits.slice(0, -scale)}.${digits.slice(-scale)}`;
58
59
  };
59
60
  /** `50000.00` as `50 000.00`: groups of three in the whole part, as a list prints an amount. */
@@ -79,6 +80,13 @@ export const minorUnits = (amount, currency, what = "an amount") => {
79
80
  `such as "${formatDecimal(5_000 * 10 ** scale, scale)}"`, "money.amount");
80
81
  return Number(units);
81
82
  };
83
+ /** Minor units for a decimal that may be negative, such as an opening balance of "-1200.50". */
84
+ export const signedMinorUnits = (amount, currency, what = "an amount") => {
85
+ if (typeof amount !== "string" || !amount.trim().startsWith("-"))
86
+ return minorUnits(amount, currency, what);
87
+ const units = minorUnits(amount.trim().slice(1), currency, what);
88
+ return units === 0 ? 0 : -units;
89
+ };
82
90
  export const moneyOf = (units, currency) => ({
83
91
  amount: formatDecimal(units, scaleOf(currency)),
84
92
  currency,