@wirecat/cli-core 0.669.0 → 0.670.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 (54) hide show
  1. package/CHANGELOG.md +76 -0
  2. package/dist/background/daily-archive-timer.d.ts +1 -1
  3. package/dist/calendar/mcp/index.d.ts +12 -12
  4. package/dist/cli/documents/words.d.ts +1 -1
  5. package/dist/cli/store-settings.js +5 -3
  6. package/dist/crm/cli/csv.d.ts +1 -1
  7. package/dist/crm/cli/csv.js +2 -2
  8. package/dist/crm/cli/index.d.ts +11 -1
  9. package/dist/crm/cli/index.js +11 -5
  10. package/dist/crm/cli/records.d.ts +94 -0
  11. package/dist/crm/cli/records.js +412 -0
  12. package/dist/crm/foreign-contacts.d.ts +34 -0
  13. package/dist/crm/foreign-contacts.js +104 -0
  14. package/dist/crm/index.d.ts +9 -3
  15. package/dist/crm/index.js +7 -1
  16. package/dist/crm/provider-call.d.ts +23 -0
  17. package/dist/crm/provider-call.js +49 -0
  18. package/dist/crm/query.d.ts +32 -0
  19. package/dist/crm/query.js +122 -0
  20. package/dist/crm/source.d.ts +41 -4
  21. package/dist/crm/sync.d.ts +1 -1
  22. package/dist/crm/sync.js +13 -7
  23. package/dist/crm/testing/source-contract.d.ts +5 -0
  24. package/dist/crm/testing/source-contract.js +39 -0
  25. package/dist/crm/testing/source.d.ts +9 -3
  26. package/dist/crm/testing/source.js +109 -10
  27. package/dist/crm/testing/write-contract.d.ts +2 -2
  28. package/dist/crm/testing/write-contract.js +41 -2
  29. package/dist/crm/values.d.ts +33 -0
  30. package/dist/crm/values.js +75 -0
  31. package/dist/crm/walk.d.ts +18 -0
  32. package/dist/crm/walk.js +23 -0
  33. package/dist/crm/writer.d.ts +41 -6
  34. package/dist/crm/writer.js +16 -10
  35. package/dist/crm/writes.d.ts +38 -2
  36. package/dist/crm/writes.js +163 -9
  37. package/dist/domain/crm.d.ts +41 -5
  38. package/dist/entities/deal.d.ts +8 -2
  39. package/dist/entities/deal.js +4 -1
  40. package/dist/errors/reasons.js +23 -2
  41. package/dist/oauth/index.d.ts +1 -1
  42. package/dist/oauth/index.js +1 -1
  43. package/dist/oauth/keeper.js +4 -0
  44. package/dist/oauth/storage.d.ts +21 -0
  45. package/dist/oauth/storage.js +32 -1
  46. package/dist/store/sqlite/crm-contacts.d.ts +5 -4
  47. package/dist/store/sqlite/crm-contacts.js +8 -4
  48. package/dist/store/sqlite/crm-rows.d.ts +1 -0
  49. package/dist/store/sqlite/crm-rows.js +37 -7
  50. package/dist/store/sqlite/crm-settings.d.ts +2 -2
  51. package/dist/store/sqlite/crm-settings.js +4 -3
  52. package/dist/store/sqlite/crm.d.ts +5 -3
  53. package/dist/store/sqlite/crm.js +20 -3
  54. package/package.json +1 -1
@@ -55,7 +55,10 @@ export const deal = v.strictObject({
55
55
  external_id: nullableText,
56
56
  /** A CRM copy's assignee, the identity `<account>/user/<id>`. */
57
57
  assignee: nullableText,
58
- /** A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. */
58
+ /**
59
+ * A CRM copy's own fields by code; a list field's value is its option's label, `option_id` its id. `amount_note` is
60
+ * WireCat's own note, not a CRM field: the CRM's amount the store could not keep, and why.
61
+ */
59
62
  provider_metadata: v.record(v.string(), v.strictObject({
60
63
  label: v.nullable(v.string()),
61
64
  value: v.unknown(),
@@ -29,6 +29,11 @@ const SIGN_IN = [
29
29
  ["oauth.no-response", "outcome_unknown", "the token request did not finish"],
30
30
  ["oauth.unavailable", "provider_unavailable", "the provider's token endpoint is unavailable"],
31
31
  ["oauth.expired", "authentication_error", "the provider refused the saved sign-in; sign in again"],
32
+ [
33
+ "oauth.moved-rotating",
34
+ "authentication_error",
35
+ "a run with moved folders cannot refresh a sign-in whose refresh token rotates",
36
+ ],
32
37
  ["oauth.invalid-response", "invalid_response", "the provider's token response could not be used"],
33
38
  ["oauth.failed", "authentication_error", "the provider returned no offline refresh token"],
34
39
  ["oauth.revoke-failed", "outcome_unknown", "the provider did not confirm the revoke"],
@@ -432,16 +437,32 @@ const OTHERS = [
432
437
  validation("pipeline.field", "a pipeline needs a name and at least one stage, each named once"),
433
438
  ["pipeline.not-found", "not_found", "no stored pipeline has that name or reference"],
434
439
  validation("crm.stage-unknown", "a CRM item stands in a stage the store does not hold; it was not kept"),
435
- validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a currency it does not keep"),
440
+ validation("crm.item-invalid", "a CRM item has a field the store refuses, such as a status it does not know"),
441
+ validation("crm.amount-unkept", "a CRM deal's amount is in a currency or with decimals the store cannot hold: the deal is kept without it"),
436
442
  validation("crm.pipeline-required", "the CRM has more than one pipeline of the kind; the command names one"),
437
443
  validation("field.unknown", "no custom field of the kind has that code or label; `fields list` lists them"),
438
444
  validation("field.ambiguous", "more than one custom field has that label; name one by its code"),
439
445
  validation("field.unknown-option", "the list field has no option with that id or label"),
446
+ validation("crm.record-ambiguous", "more than one contact or company has that name; name one by its id"),
447
+ validation("field.ambiguous-option", "more than one option of the list field has that label; name one by its id"),
440
448
  validation("field.unknown-kind", "fields are listed for deals, leads, people and organizations only"),
449
+ [
450
+ "crm.foreign-contacts-spent",
451
+ "permission_error",
452
+ "the day's views of contacts and companies that are not yours are spent",
453
+ ],
454
+ [
455
+ "crm.client-reads-admin-only",
456
+ "permission_error",
457
+ "a raw api call that reads contacts or companies is the CRM administrator's",
458
+ ],
459
+ validation("field.not-filterable", "the CRM cannot filter a list by that custom field"),
460
+ validation("query.bad-value", "a term's value is not the kind its field takes, such as an id or a number"),
461
+ validation("crm.record-field", "a contact's or company's field is not valid"),
441
462
  validation("crm.write-unsupported", "the CRM does not take this write, or does not recognise a repeated one"),
442
463
  validation("crm.unlisted-held", "a list of every id would mark most of a kind deleted; nothing was, until --rescan"),
443
464
  validation("crm.narrowing-held", "the default scope mine would mark most of a kind's stored rows deleted; none is, until the owner sets the scope"),
444
- validation("crm.unassigned-dropped", "the CRM does not let this sign-in count a user in unassigned as nobody's; that user's deals are not copied"),
465
+ validation("crm.unassigned-dropped", "the CRM does not let this sign-in choose a user in unassigned; that user's deals are not copied"),
445
466
  validation("crm.not-reported", "the CRM did not list users or departments; what they would say is unknown, nothing withdrawn"),
446
467
  validation("crm.reference-unknown", "a CRM row names a contact, company or user the store does not hold; that link was not made"),
447
468
  validation("crm.pending-dropped", "relationships waited too long for an end that never came; they were dropped"),
@@ -3,4 +3,4 @@ export { type ClientFileOptions, readClientFile } from "./client-file.js";
3
3
  export { type SignInOptions, type TokenKeeper, type TokenKeeperOptions, type TokensOptions, tokenKeeper, } from "./keeper.js";
4
4
  export { type AppSource, type ExchangeContext, googleProvider, type OAuthClient, type OAuthProvider, type RequestContext, type TokenSet, } from "./provider.js";
5
5
  export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
6
- export { type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
6
+ export { accountTokenCodec, type CredentialStorageOptions, credentialStorage, driveSessionCodec, type EncodeInput, googleTokenCodec, oauthAccount, type StoredTokens, standardCodec, type TokenCodec, type TokenStorage, zoomTokenCodec, } from "./storage.js";
@@ -3,4 +3,4 @@ export { readClientFile } from "./client-file.js";
3
3
  export { tokenKeeper, } from "./keeper.js";
4
4
  export { googleProvider, } from "./provider.js";
5
5
  export { requestTokens, revokeToken, TOKEN_LOG_ALLOW, TOKEN_LOG_EVENT } from "./requests.js";
6
- export { credentialStorage, driveSessionCodec, googleTokenCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
6
+ export { accountTokenCodec, credentialStorage, driveSessionCodec, googleTokenCodec, oauthAccount, standardCodec, zoomTokenCodec, } from "./storage.js";
@@ -120,6 +120,10 @@ export const tokenKeeper = (options) => {
120
120
  if (fresh(current.tokens) || current.tokens.refreshToken !== seen.tokens.refreshToken)
121
121
  return current.tokens;
122
122
  }
123
+ if (storage.moved && storage.rotating)
124
+ throw new CliError("authentication_error", `the sign-in to ${provider.name} needs a refresh, which a run with moved folders never makes: the ` +
125
+ "provider rotates its refresh token, and the owner's own sign-in would keep a dead one; run this in " +
126
+ "the normal run, or sign in again there", { reason: "oauth.moved-rotating" });
123
127
  const client = clientOf(current);
124
128
  const refreshed = await exchange({ grant_type: "refresh_token", refresh_token: current.tokens.refreshToken }, context(client, current.tokens));
125
129
  // A rotated refresh token is saved even so: kept only in memory, it would die with the process.
@@ -4,6 +4,11 @@ export interface StoredTokens {
4
4
  tokens: TokenSet;
5
5
  /** The app the entry was signed in with, when the entry records it; refresh must use that one. */
6
6
  client?: OAuthClient;
7
+ /** The account an account-bound entry (`accountTokenCodec`) was signed in to: its base URL and the user's id. */
8
+ account?: {
9
+ host: string;
10
+ userId: string;
11
+ };
7
12
  }
8
13
  export interface EncodeInput {
9
14
  tokens: TokenSet;
@@ -12,11 +17,15 @@ export interface EncodeInput {
12
17
  previous?: string;
13
18
  /** Fields a CLI adds at sign-in, such as drive's `principal`. */
14
19
  extra?: Record<string, unknown>;
20
+ /** A new sign-in, not a refresh: a codec takes the account's fields from `extra` only. */
21
+ signIn?: boolean;
15
22
  }
16
23
  /** Every failure throws a fixed message: a parser's message would quote the secret. */
17
24
  export interface TokenCodec {
18
25
  decode(raw: string): StoredTokens;
19
26
  encode(input: EncodeInput): string;
27
+ /** The provider gives a new refresh token on every refresh and kills the old one (amoCRM, Kommo). */
28
+ readonly rotating?: boolean;
20
29
  }
21
30
  export interface TokenStorage {
22
31
  /** Names the entry across processes; the lock is keyed by it. */
@@ -26,6 +35,11 @@ export interface TokenStorage {
26
35
  * instead of copying the owner's sign-in there. Only a new sign-in is saved.
27
36
  */
28
37
  readonly moved?: boolean;
38
+ /**
39
+ * The codec's `rotating`: a moved run then never refreshes, since the rotated token would land in its temporary
40
+ * entry and the owner's own entry would keep a dead one.
41
+ */
42
+ readonly rotating?: boolean;
29
43
  /** Throws when the entry cannot be saved, so a sign-in fails before the browser, not after consent. */
30
44
  probe(): void;
31
45
  read(): StoredTokens | undefined;
@@ -46,6 +60,13 @@ export declare const driveSessionCodec: TokenCodec;
46
60
  * client file is read only at sign-in. A client without a secret drops the one the profile signed in with before.
47
61
  */
48
62
  export declare const googleTokenCodec: TokenCodec;
63
+ /**
64
+ * An entry bound to one CRM account through the owner's own app (Bitrix24's local application, a Kommo
65
+ * integration): the standard entry plus the owner's client secret, which every refresh needs, the account's base URL
66
+ * (`host`) and the signed-in user's id. A sign-in passes `host` and `userId` as `extra`; a refresh keeps them, and
67
+ * saves a rotated refresh token. A moved run's writes go to its temporary entry (`credentialStorage`).
68
+ */
69
+ export declare const accountTokenCodec: (providerId: string) => TokenCodec;
49
70
  /** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
50
71
  export declare const zoomTokenCodec: TokenCodec;
51
72
  export interface CredentialStorageOptions {
@@ -142,6 +142,36 @@ export const googleTokenCodec = {
142
142
  return JSON.stringify(entry);
143
143
  },
144
144
  };
145
+ /**
146
+ * An entry bound to one CRM account through the owner's own app (Bitrix24's local application, a Kommo
147
+ * integration): the standard entry plus the owner's client secret, which every refresh needs, the account's base URL
148
+ * (`host`) and the signed-in user's id. A sign-in passes `host` and `userId` as `extra`; a refresh keeps them, and
149
+ * saves a rotated refresh token. A moved run's writes go to its temporary entry (`credentialStorage`).
150
+ */
151
+ export const accountTokenCodec = (providerId) => {
152
+ const standard = standardCodec(providerId);
153
+ return {
154
+ rotating: true,
155
+ decode: (raw) => {
156
+ const stored = standard.decode(raw);
157
+ const value = parse(raw);
158
+ const clientSecret = text(value.clientSecret);
159
+ const host = text(value.host);
160
+ const userId = text(value.userId);
161
+ if (!host || !userId || !clientSecret)
162
+ throw invalid();
163
+ return { ...stored, client: { ...stored.client, clientSecret }, account: { host, userId } };
164
+ },
165
+ encode: (input) => {
166
+ const entry = parse(standard.encode(input));
167
+ const from = input.signIn ? (input.extra ?? {}) : entry;
168
+ if (!input.client.clientSecret || typeof from.host !== "string" || typeof from.userId !== "string")
169
+ throw new CliError("configuration_error", "an account-bound sign-in needs the app's secret, its host and user");
170
+ entry.clientSecret = input.client.clientSecret;
171
+ return JSON.stringify(entry);
172
+ },
173
+ };
174
+ };
145
175
  /** zm's entry as zoom-cli writes it today: `{accessToken, refreshToken, expiresAt, scopes}`, all four required. */
146
176
  export const zoomTokenCodec = {
147
177
  decode: (raw) => {
@@ -218,6 +248,7 @@ export const credentialStorage = (options) => {
218
248
  return {
219
249
  key: `${service}\u0000${account}`,
220
250
  moved,
251
+ ...(codec.rotating ? { rotating: true } : {}),
221
252
  probe: () => {
222
253
  raw(account);
223
254
  },
@@ -225,7 +256,7 @@ export const credentialStorage = (options) => {
225
256
  const value = current();
226
257
  return value === undefined ? undefined : codec.decode(value);
227
258
  },
228
- write: (input, writeOptions) => save(codec.encode({ ...input, previous: raw(account) }), writeOptions),
259
+ write: (input, writeOptions) => save(codec.encode({ ...input, previous: raw(account), ...(writeOptions?.signIn ? { signIn: true } : {}) }), writeOptions),
229
260
  remove: () => {
230
261
  try {
231
262
  return credentials.remove(account);
@@ -14,10 +14,11 @@ export interface CrmContactsRemoved {
14
14
  export declare const withoutPlaceholder: (name: string) => string | null;
15
15
  /**
16
16
  * Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
17
- * `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
18
- * about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
19
- * its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
20
- * after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
17
+ * `users` when given) names in a client's role, that is no contact of a kept company, and that the CRM does not
18
+ * assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
19
+ * saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
20
+ * deleted unless anything still points at them. People named after a contact keep that name without the import's
21
+ * `null #<id>`; the owner's person is never renamed.
21
22
  */
22
23
  export declare const removeCrmContacts: (context: StoreContext, key: AccountKey, { users, before, dryRun }: {
23
24
  users?: readonly string[];
@@ -14,10 +14,11 @@ class DryRun extends Error {
14
14
  const NONE = { contacts: 0, persons: 0, personsKept: 0, names: 0 };
15
15
  /**
16
16
  * Removes, in one transaction, every contact of the account that no kept deal or lead (not deleted, and inside
17
- * `users` when given) names in a client's role, and that is no contact of a kept company. A contact the owner decided
18
- * about, or one anything else points at, stays; so does one saved at or after `before`, whose deal may still be on
19
- * its way. A person the removed contacts leave empty is deleted unless anything still points at them. People named
20
- * after a contact keep that name without the import's `null #<id>`; the owner's person is never renamed.
17
+ * `users` when given) names in a client's role, that is no contact of a kept company, and that the CRM does not
18
+ * assign to one of `users`. A contact the owner decided about, or one anything else points at, stays; so does one
19
+ * saved at or after `before`, whose deal may still be on its way. A person the removed contacts leave empty is
20
+ * deleted unless anything still points at them. People named after a contact keep that name without the import's
21
+ * `null #<id>`; the owner's person is never renamed.
21
22
  */
22
23
  export const removeCrmContacts = (context, key, { users, before, dryRun = false }) => {
23
24
  const { database } = context;
@@ -55,6 +56,9 @@ export const removeCrmContacts = (context, key, { users, before, dryRun = false
55
56
  .prepare("INSERT INTO temp.crm_gone SELECT i.id, l.person_id FROM identities i " +
56
57
  `LEFT JOIN identity_links l ON l.identity_id = i.id WHERE ${contactOf} ` +
57
58
  "AND i.created_at < ? AND i.updated_at < ? " +
59
+ (users === undefined
60
+ ? ""
61
+ : "AND coalesce(json_extract(i.metadata, '$.assignee'), '') NOT IN (SELECT id FROM temp.crm_scope) ") +
58
62
  `AND NOT ${named("deals", "deal")} AND NOT ${named("leads", "lead")} ` +
59
63
  "AND NOT EXISTS (SELECT 1 FROM links k JOIN records r ON r.entity_type = 'organization' " +
60
64
  "AND r.entity_id = k.to_id WHERE k.from_type = 'person' AND k.from_id = l.person_id " +
@@ -40,5 +40,6 @@ export declare const crmRowsOver: (context: StoreContext) => {
40
40
  savePipeline: (accountId: number, kind: DealKind, pipeline: CrmPipeline, at: number) => number;
41
41
  saveItemRow: (key: AccountKey, accountId: number, kind: DealKind, item: CrmItem, at: number, writer?: ItemWriter) => CrmSkipped | {
42
42
  id: number;
43
+ amountNote?: string;
43
44
  };
44
45
  };
@@ -1,9 +1,42 @@
1
1
  import { CliError } from "@wirecat/cli-base";
2
2
  import { STAGE_OUTCOMES } from "../../domain/deals.js";
3
- import { currencyOf, minorUnits } from "../../domain/money.js";
3
+ import { currencyOf, minorUnits, scaleOf } from "../../domain/money.js";
4
4
  import { fold } from "../normalize.js";
5
5
  import { authorActor } from "./memories.js";
6
6
  export const TABLES = { deal: "deals", lead: "leads" };
7
+ const MONEY_REFUSALS = ["money.currency", "money.amount"];
8
+ const amountFault = (item, code) => {
9
+ const text = String(item.amount).trim();
10
+ const decimal = /^\d+(?:\.(\d+))?$/.exec(text);
11
+ if (text.startsWith("-"))
12
+ return "it is below zero";
13
+ if (!decimal)
14
+ return "it is not a decimal number";
15
+ if ((decimal[1] ?? "").length > scaleOf(String(code)))
16
+ return `it has more decimals than ${code} has`;
17
+ return "it is too large to keep exactly";
18
+ };
19
+ /** A deal is never dropped over its money: what the store cannot hold is left out, and the deal says why. */
20
+ const moneyOf = (item) => {
21
+ if (item.amount == null || item.currency == null)
22
+ return { currency: null, amount: null, amountNote: null };
23
+ try {
24
+ const currency = currencyOf(item.currency);
25
+ return { currency, amount: minorUnits(String(item.amount), currency), amountNote: null };
26
+ }
27
+ catch (error) {
28
+ const reason = error instanceof CliError ? error.details?.reason : undefined;
29
+ if (!MONEY_REFUSALS.includes(reason))
30
+ throw error;
31
+ const code = textOf(String(item.currency), 10);
32
+ const why = reason === "money.currency" ? `the store keeps no amounts in ${code}` : amountFault(item, code);
33
+ return {
34
+ currency: null,
35
+ amount: null,
36
+ amountNote: `the CRM's amount ${textOf(String(item.amount), 40)} ${code} is not kept: ${why}`,
37
+ };
38
+ }
39
+ };
7
40
  /** Who writes a CRM's copies: the sync, not an agent, so `author.kind` is `rule`. */
8
41
  export const SOURCE = "crm";
9
42
  /**
@@ -123,11 +156,7 @@ export const crmRowsOver = (context) => {
123
156
  message: `${kind} ${item.externalId} stands in stage ${item.stage} of pipeline ${item.pipeline}, which is not stored`,
124
157
  };
125
158
  const title = textOf(item.title, 200) ?? `${kind} ${item.externalId}`;
126
- const given = item.amount != null && item.currency != null;
127
- const currency = given ? currencyOf(item.currency) : null;
128
- const amount = currency === null ? null : minorUnits(String(item.amount), currency, `${kind} ${item.externalId}'s amount`);
129
- if (amount !== null && amount < 0)
130
- throw new CliError("validation_error", "an amount is 0 or more");
159
+ const { currency, amount, amountNote } = moneyOf(item);
131
160
  if (item.status != null && !STAGE_OUTCOMES.includes(item.status))
132
161
  throw new CliError("validation_error", `${kind} ${item.externalId}'s status is open, won or lost`);
133
162
  const status = item.status ?? String(stage.outcome);
@@ -148,6 +177,7 @@ export const crmRowsOver = (context) => {
148
177
  ...(textOf(item.contactName, 200) ? { contact_name: textOf(item.contactName, 200) } : {}),
149
178
  ...(textOf(item.companyName, 200) ? { company_name: textOf(item.companyName, 200) } : {}),
150
179
  ...(item.closedReason && status !== "open" ? { closed_reason: textOf(item.closedReason, 2000) } : {}),
180
+ ...(amountNote ? { amount_note: { label: "Amount not kept", value: amountNote } } : {}),
151
181
  };
152
182
  const values = {
153
183
  title,
@@ -191,7 +221,7 @@ export const crmRowsOver = (context) => {
191
221
  }
192
222
  if (writer.project !== undefined)
193
223
  database.prepare(`UPDATE ${table} SET project_id = ? WHERE id = ?`).run(writer.project, id);
194
- return { id };
224
+ return { id, ...(amountNote ? { amountNote } : {}) };
195
225
  };
196
226
  return { savePipeline, saveItemRow };
197
227
  };
@@ -8,7 +8,7 @@ export type CrmLinkMode = (typeof CRM_LINK_MODES)[number];
8
8
  /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
9
9
  export declare const COMPANY_TYPE_MEANINGS: readonly ["customer-of", "supplier", "partner-of"];
10
10
  export type CompanyTypeMeaning = (typeof COMPANY_TYPE_MEANINGS)[number];
11
- /** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
11
+ /** `mine`: only the deals and leads of the `unassigned` users, else of the sign-in's own user; `all`: every one. */
12
12
  export declare const CRM_SCOPES: readonly ["mine", "all"];
13
13
  /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
14
14
  export declare const CRM_ACTIVITIES: readonly ["on", "off"];
@@ -28,7 +28,7 @@ export declare const crmActivitiesOn: (database: CacheDatabase, key: AccountKey)
28
28
  export declare const crmCompanyTypes: (database: CacheDatabase, key: AccountKey) => Record<string, CompanyTypeMeaning>;
29
29
  /** `mine` unless the owner chose `all`: a sync never copies other people's deals without being asked. */
30
30
  export declare const crmScope: (database: CacheDatabase, key: AccountKey) => CrmScopeSetting;
31
- /** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
31
+ /** The users whose deals and leads scope mine keeps, whatever the scope is now: the `unassigned` list, else `self`. */
32
32
  export declare const crmScopeUsers: (database: CacheDatabase, key: AccountKey) => string[];
33
33
  /**
34
34
  * `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
@@ -4,7 +4,7 @@ import { isCrmUserId, normalCrmUserId } from "../../domain/crm.js";
4
4
  export const CRM_LINK_MODES = ["reported", "review"];
5
5
  /** What a CRM company type may mean: the company buys from the own company, sells to it, or partners with it. */
6
6
  export const COMPANY_TYPE_MEANINGS = ["customer-of", "supplier", "partner-of"];
7
- /** `mine`: only the deals and leads of the sign-in's own user and of the `unassigned` users; `all`: every one. */
7
+ /** `mine`: only the deals and leads of the `unassigned` users, else of the sign-in's own user; `all`: every one. */
8
8
  export const CRM_SCOPES = ["mine", "all"];
9
9
  /** `activities`: whether a sync also reads the activities and tasks on the deals and leads it keeps; off by default. */
10
10
  export const CRM_ACTIVITIES = ["on", "off"];
@@ -57,10 +57,11 @@ const picked = (name, text, values) => {
57
57
  throw new CliError("validation_error", `a CRM account's ${name} setting is ${values.join(" or ")}`);
58
58
  return text;
59
59
  };
60
- /** The users whose deals and leads scope mine keeps, whatever the scope is now: `self` and the `unassigned` list. */
60
+ /** The users whose deals and leads scope mine keeps, whatever the scope is now: the `unassigned` list, else `self`. */
61
61
  export const crmScopeUsers = (database, key) => {
62
62
  const self = crmOwnUser(database, key);
63
- return [...new Set([...(self ? [self] : []), ...userIds(stored(database, crmSettingKey(key, "unassigned")))])];
63
+ const chosen = userIds(stored(database, crmSettingKey(key, "unassigned")));
64
+ return [...new Set(chosen.length ? chosen : self ? [self] : [])];
64
65
  };
65
66
  /**
66
67
  * `links`: reported or review; `scope`: mine or all; `unassigned`: the CRM's user ids, comma-separated;
@@ -15,7 +15,7 @@ import type { StoreContext } from "./open.js";
15
15
  export interface CrmRelationIssue {
16
16
  /** The CRM row it came from; absent for the account as a whole. */
17
17
  externalId?: string;
18
- reason: "crm.reference-unknown" | "crm.own-unknown" | "crm.email-ambiguous" | "relationship.reference-unknown" | "relationship.invalid";
18
+ reason: "crm.reference-unknown" | "crm.own-unknown" | "crm.email-ambiguous" | "crm.amount-unkept" | "relationship.reference-unknown" | "relationship.invalid";
19
19
  message: string;
20
20
  }
21
21
  export interface CrmSaved {
@@ -74,10 +74,12 @@ export interface CrmCopies {
74
74
  /**
75
75
  * After a complete list of the kind's ids: marks deleted every stored one the list lacks that the CRM has not
76
76
  * changed since `before` (epoch ms), so a row made while the list was read is never taken for a deleted one.
77
- * `dryRun` only counts them.
77
+ * With `users`, only a deal or lead with no assignee or assigned to one of them: a list read under that scope
78
+ * names no other. `dryRun` only counts them.
78
79
  */
79
80
  removeUnlisted(key: AccountKey, kind: CrmKind, listed: string[], before: number, options?: {
80
81
  dryRun?: boolean;
82
+ users?: readonly string[];
81
83
  }): Promise<number>;
82
84
  /** Which deals and leads the account's sync copies: its `scope` and `unassigned` settings. */
83
85
  scope(key: AccountKey): Promise<CrmScopeSetting>;
@@ -118,7 +120,7 @@ export interface CrmCopies {
118
120
  /**
119
121
  * Removes the contacts no kept deal, lead or company names, and the people they leave empty; see
120
122
  * `removeCrmContacts`. A deal or lead assigned to a user outside `users` counts as gone; without `users`, outside
121
- * those scope mine keeps (`self` and `unassigned`), whatever the scope is now. `dryRun` only counts.
123
+ * those scope mine keeps (`unassigned`, else `self`), whatever the scope is now. `dryRun` only counts.
122
124
  */
123
125
  removeContacts(key: AccountKey, options: {
124
126
  users?: readonly string[];
@@ -283,6 +283,8 @@ export const crmCopiesOver = (context, people) => {
283
283
  const saved = saveItemRow(key, accountId, kind, item, at);
284
284
  if ("reason" in saved)
285
285
  return saved;
286
+ if (saved.amountNote)
287
+ report.tally.issues.push({ externalId: item.externalId, reason: "crm.amount-unkept", message: saved.amountNote });
286
288
  const { id } = saved;
287
289
  if (item.people === undefined && item.assignee === undefined)
288
290
  return null;
@@ -311,6 +313,15 @@ export const crmCopiesOver = (context, people) => {
311
313
  reportFrom(key, accountId, self, wanted, scope, report.tally, report.pending);
312
314
  return null;
313
315
  };
316
+ /** Kept in the identity's metadata, as a deal keeps its own, so the contact cleanup under `mine` can read it. */
317
+ const assignContact = (key, externalId, assignee) => {
318
+ const user = assignee ? crmIdentityId(key, normalCrmUserId(assignee), "user") : null;
319
+ database
320
+ .prepare("UPDATE identities SET metadata = CASE WHEN ? IS NULL THEN json_remove(metadata, '$.assignee') " +
321
+ "ELSE json_set(coalesce(metadata, '{}'), '$.assignee', ?) END " +
322
+ "WHERE provider = ? AND external_id = ? AND json_extract(metadata, '$.assignee') IS NOT ?")
323
+ .run(user, user, key.provider, crmIdentityId(key, externalId), user);
324
+ };
314
325
  const saveItems = (key, kind, items, users) => write(database, () => {
315
326
  const accountId = account(key);
316
327
  const at = now();
@@ -497,7 +508,8 @@ export const crmCopiesOver = (context, people) => {
497
508
  "AND deleted_at IS NULL")
498
509
  .all(accountId)
499
510
  : database
500
- .prepare(`SELECT id, external_id, updated_at FROM ${TABLES[kind]} WHERE account_id = ? AND deleted_at IS NULL`)
511
+ .prepare(`SELECT id, external_id, updated_at, json_extract(metadata, '$.assignee') AS assignee FROM ${TABLES[kind]} ` +
512
+ "WHERE account_id = ? AND deleted_at IS NULL")
501
513
  .all(accountId);
502
514
  };
503
515
  const markDeleted = (key, kind, rows) => {
@@ -532,6 +544,8 @@ export const crmCopiesOver = (context, people) => {
532
544
  const tally = tallied();
533
545
  const pending = pendingBook(accountId);
534
546
  for (const contact of contacts) {
547
+ if (contact.assignee !== undefined)
548
+ assignContact(key, contact.externalId, contact.assignee);
535
549
  const person = nameUnnamed(key, contact.externalId, "contact", textOf(contact.name, 200));
536
550
  const email = textOf(contact.email, 320)?.toLowerCase();
537
551
  const sharing = email ? peopleSharing(key, contact.externalId, email) : 0;
@@ -584,9 +598,12 @@ export const crmCopiesOver = (context, people) => {
584
598
  const gone = new Set(externalIds);
585
599
  return markDeleted(key, kind, stored(key, kind).filter((row) => gone.has(String(row.external_id))));
586
600
  }),
587
- removeUnlisted: async (key, kind, listed, before, { dryRun } = {}) => write(database, () => {
601
+ removeUnlisted: async (key, kind, listed, before, { dryRun, users } = {}) => write(database, () => {
588
602
  const held = new Set(listed);
589
- const gone = stored(key, kind).filter((row) => !held.has(String(row.external_id)) && Number(row.updated_at) < before);
603
+ const scope = users && new Set(users.map((id) => crmIdentityId(key, id, "user")));
604
+ const gone = stored(key, kind).filter((row) => !held.has(String(row.external_id)) &&
605
+ Number(row.updated_at) < before &&
606
+ (!scope || row.assignee == null || scope.has(String(row.assignee))));
590
607
  return dryRun ? gone.length : markDeleted(key, kind, gone);
591
608
  }),
592
609
  scope: async (key) => crmScope(database, key),
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wirecat/cli-core",
3
- "version": "0.669.0",
3
+ "version": "0.670.0",
4
4
  "description": "The messenger-neutral half of a messaging CLI: domain model, message locators, rendering, name resolution, the SQLite seam, the command skeleton and shared read commands, the send guard, run records and the message store",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Viacheslav Ptsarev",