@wirecat/cli-core 0.721.0 → 0.723.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/CHANGELOG.md +90 -0
- package/dist/background/daily-archive-timer.d.ts +1 -1
- package/dist/cli/messenger/lacks.d.ts +2 -1
- package/dist/cli/messenger/lacks.js +14 -1
- package/dist/cli/service-api-call.d.ts +6 -0
- package/dist/cli/service-api-call.js +21 -9
- package/dist/cli/service-api.d.ts +5 -0
- package/dist/cli/service-api.js +11 -0
- package/dist/cli/token-session.d.ts +2 -1
- package/dist/cli/token-session.js +2 -2
- package/dist/crm/cli/account.d.ts +60 -0
- package/dist/crm/cli/account.js +147 -0
- package/dist/crm/cli/files.js +2 -1
- package/dist/crm/cli/index.d.ts +3 -0
- package/dist/crm/cli/index.js +4 -0
- package/dist/crm/foreign-contacts.js +2 -1
- package/dist/crm/index.d.ts +3 -2
- package/dist/crm/index.js +1 -0
- package/dist/crm/manifest/manifest.d.ts +60 -1
- package/dist/crm/manifest/manifest.js +88 -0
- package/dist/crm/manifest/source.d.ts +22 -3
- package/dist/crm/manifest/source.js +10 -3
- package/dist/crm/manifest/writer.d.ts +39 -0
- package/dist/crm/manifest/writer.js +298 -0
- package/dist/crm/state-folders.d.ts +5 -0
- package/dist/crm/state-folders.js +2 -0
- package/dist/crm/testing/index.d.ts +1 -1
- package/dist/crm/testing/index.js +1 -1
- package/dist/crm/testing/manifest-fake.d.ts +14 -0
- package/dist/crm/testing/manifest-fake.js +252 -27
- package/dist/errors/reasons.d.ts +1 -1
- package/dist/errors/reasons.js +11 -0
- package/dist/ports/wirecat-tools.js +7 -0
- package/dist/services/files/mirror.d.ts +5 -2
- package/dist/services/files/mirror.js +1 -1
- package/dist/services/metadata.d.ts +1 -1
- package/dist/store/index.d.ts +1 -0
- package/dist/store/sqlite/account-purge.js +3 -0
- package/dist/store/sqlite/crm-stage-entries.js +4 -1
- package/dist/store/sqlite/erase-plan.d.ts +19 -0
- package/dist/store/sqlite/erase-plan.js +74 -0
- package/dist/store/sqlite/messages.js +2 -1
- package/dist/store/sqlite/organization-erase.d.ts +29 -0
- package/dist/store/sqlite/organization-erase.js +83 -0
- package/dist/store/sqlite/organizations.d.ts +10 -1
- package/dist/store/sqlite/organizations.js +6 -1
- package/dist/store/sqlite/person-erase.js +4 -45
- package/package.json +2 -2
|
@@ -5,6 +5,7 @@ import type { ContractCase } from "../../meetings/index.js";
|
|
|
5
5
|
import { type CrmManifest, type CrmManifestHooks } from "../manifest/manifest.js";
|
|
6
6
|
import { type CrmRaw } from "../values.js";
|
|
7
7
|
import { type CrmSourceFixture } from "./source-contract.js";
|
|
8
|
+
import { type CrmWriteFixture } from "./write-contract.js";
|
|
8
9
|
type Definitions = Readonly<Record<string, SchemaNode>>;
|
|
9
10
|
export interface CrmManifestFakeOptions {
|
|
10
11
|
/** The generated API manifest the source manifest names its operations in. */
|
|
@@ -21,6 +22,10 @@ export interface CrmManifestFake extends FakeApi {
|
|
|
21
22
|
deny(kind: CrmKind, id: string, status: number): void;
|
|
22
23
|
/** Moves one row's change time to now, for the next read of changes to list it. */
|
|
23
24
|
touch(kind: CrmKind, id: string): void;
|
|
25
|
+
/** Makes the next write's answer lost after the service made the change, as a dropped connection does. */
|
|
26
|
+
loseNextAnswer(): void;
|
|
27
|
+
/** How many write requests reached the service so far. */
|
|
28
|
+
requests(): number;
|
|
24
29
|
}
|
|
25
30
|
export declare const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
|
|
26
31
|
/**
|
|
@@ -44,4 +49,13 @@ export declare const crmManifestFixture: (manifest: CrmManifest, options: CrmMan
|
|
|
44
49
|
* test runs, `for (const { name, run } of crmManifestContract(SOURCE, { api, definitions })) it(name, run)`.
|
|
45
50
|
*/
|
|
46
51
|
export declare const crmManifestContract: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => ContractCase[];
|
|
52
|
+
/**
|
|
53
|
+
* A `crmWriteContract` fixture for a writer built from a manifest's `writes`, over `crmManifestFake`: the writer, the
|
|
54
|
+
* first pipeline of the deal kind it writes, the service's own names of stage and owner, and the fake.
|
|
55
|
+
*/
|
|
56
|
+
export declare const crmManifestWriteFixture: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => Promise<CrmWriteFixture & {
|
|
57
|
+
fake: CrmManifestFake;
|
|
58
|
+
}>;
|
|
59
|
+
/** `crmWriteContract` over `crmManifestWriteFixture`, each case failing too when the fake refused a call. */
|
|
60
|
+
export declare const crmManifestWriteContract: (manifest: CrmManifest, options: CrmManifestFixtureOptions) => ContractCase[];
|
|
47
61
|
export {};
|
|
@@ -1,18 +1,22 @@
|
|
|
1
1
|
import { fakeApi, sampleOf, } from "@wirecat/cli-base/codegen";
|
|
2
|
-
import { serviceApiCall } from "../../cli/service-api-call.js";
|
|
2
|
+
import { serviceApiCall, serviceApiSend } from "../../cli/service-api-call.js";
|
|
3
3
|
import { manifestBaseUrl } from "../../cli/service-api-manifest.js";
|
|
4
4
|
import { DEAL_KINDS } from "../../domain/deals.js";
|
|
5
|
-
import { parseCrmManifest, } from "../manifest/manifest.js";
|
|
6
|
-
import { at, convert, evaluate, FIELDS, MISSING } from "../manifest/map.js";
|
|
5
|
+
import { CRM_LIST_FIELDS, parseCrmManifest, } from "../manifest/manifest.js";
|
|
6
|
+
import { at, convert, evaluate, FIELDS, MISSING, mapRecord } from "../manifest/map.js";
|
|
7
7
|
import { itemOf, resolve, step, walk } from "../manifest/paths.js";
|
|
8
8
|
import { crmSourceFromManifest } from "../manifest/source.js";
|
|
9
|
+
import { crmWriterFromManifest } from "../manifest/writer.js";
|
|
9
10
|
import { id, isRaw } from "../values.js";
|
|
10
11
|
import { crmSourceContract } from "./source-contract.js";
|
|
12
|
+
import { crmWriteContract } from "./write-contract.js";
|
|
11
13
|
export const FAKE_MANIFEST_TOKEN = "fake-manifest-token";
|
|
12
14
|
/** Three rows in pages of two: every kind pages at least once, whatever limit the manifest asks for. */
|
|
13
15
|
const ROWS = 3;
|
|
14
16
|
const PAGE = 2;
|
|
15
17
|
const SEEDED = Date.parse("2026-11-01T10:00:00Z");
|
|
18
|
+
/** The currency of every amount, and what a fixed currency reads. */
|
|
19
|
+
const CURRENCY = "EUR";
|
|
16
20
|
/** Where a rule can be written to: the first path it reads, or none for a function or a list it walks. */
|
|
17
21
|
const pathOf = (rule) => {
|
|
18
22
|
if (rule === undefined || typeof rule === "function")
|
|
@@ -29,26 +33,58 @@ const pathOf = (rule) => {
|
|
|
29
33
|
return rule.all[0];
|
|
30
34
|
return rule.path;
|
|
31
35
|
};
|
|
32
|
-
const
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
if (!Array.isArray(value) && !isRaw(value))
|
|
37
|
-
return undefined;
|
|
38
|
-
for (const [key, inner] of Object.entries(value)) {
|
|
39
|
-
const found = find(inner, [...trail, key]);
|
|
40
|
-
if (found)
|
|
41
|
-
return found;
|
|
42
|
-
}
|
|
36
|
+
const trailOf = (value, placeholder, trail = []) => {
|
|
37
|
+
if (value === placeholder)
|
|
38
|
+
return trail;
|
|
39
|
+
if (!Array.isArray(value) && !isRaw(value))
|
|
43
40
|
return undefined;
|
|
44
|
-
|
|
41
|
+
for (const [key, inner] of Object.entries(value)) {
|
|
42
|
+
const found = trailOf(inner, placeholder, [...trail, key]);
|
|
43
|
+
if (found)
|
|
44
|
+
return found;
|
|
45
|
+
}
|
|
46
|
+
return undefined;
|
|
47
|
+
};
|
|
48
|
+
const placeOf = (call, placeholder) => {
|
|
45
49
|
for (const where of ["path", "query", "body"]) {
|
|
46
|
-
const found =
|
|
50
|
+
const found = trailOf(call[where], placeholder);
|
|
47
51
|
if (found)
|
|
48
|
-
return { in: where, path: found.join(".") };
|
|
52
|
+
return { in: where, path: found.length ? found.join(".") : "." };
|
|
49
53
|
}
|
|
50
54
|
return undefined;
|
|
51
55
|
};
|
|
56
|
+
/**
|
|
57
|
+
* Our fields, in the names a read maps, that a write's values give: each rule read backwards, `"{value}"` in its
|
|
58
|
+
* `each` the place of ours. A value the service clears with is a cleared field.
|
|
59
|
+
*/
|
|
60
|
+
const givenOf = (spec, values) => {
|
|
61
|
+
const given = {};
|
|
62
|
+
if (!isRaw(values))
|
|
63
|
+
return given;
|
|
64
|
+
const clear = JSON.stringify(spec.clear === undefined ? null : spec.clear);
|
|
65
|
+
for (const [field, rule] of Object.entries(spec.fields)) {
|
|
66
|
+
if (typeof rule !== "object" || !("to" in rule) || !(rule.to in values))
|
|
67
|
+
continue;
|
|
68
|
+
const name = field === "owner" ? "assignee" : field;
|
|
69
|
+
const list = CRM_LIST_FIELDS.includes(field);
|
|
70
|
+
const raw = values[rule.to];
|
|
71
|
+
if (JSON.stringify(raw) === clear) {
|
|
72
|
+
given[name] = list ? [] : null;
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
const trail = rule.each === undefined ? [] : (trailOf(rule.each, "{value}") ?? []);
|
|
76
|
+
const found = (rule.list ? (Array.isArray(raw) ? raw : []) : [raw])
|
|
77
|
+
.map((one) => (trail.length ? at(one, trail.join(".")) : one))
|
|
78
|
+
.filter((one) => one !== undefined && one !== null)
|
|
79
|
+
.map(String);
|
|
80
|
+
if (list)
|
|
81
|
+
given[name] = field === "people" ? found.map((one) => ({ externalId: one, role: "contact" })) : found;
|
|
82
|
+
// A key several rules write together is replaced whole: a part it leaves out is gone.
|
|
83
|
+
else
|
|
84
|
+
given[name] = found[0] ?? null;
|
|
85
|
+
}
|
|
86
|
+
return given;
|
|
87
|
+
};
|
|
52
88
|
const readPlace = (call, place) => {
|
|
53
89
|
if (place.in === "body")
|
|
54
90
|
return at(call.body, place.path);
|
|
@@ -288,15 +324,19 @@ export const crmManifestFake = (input, options) => {
|
|
|
288
324
|
const index = manifest.kinds.indexOf(kind);
|
|
289
325
|
return index < 0 ? undefined : String((index + 1) * 1000 + n + 1);
|
|
290
326
|
};
|
|
291
|
-
/** A
|
|
292
|
-
const
|
|
293
|
-
if (typeof rule !== "object" || !("each" in rule)
|
|
327
|
+
/** A list a rule walks, one entry for each value: a deal's people, a contact's e-mails. */
|
|
328
|
+
const putEach = (row, rule, node, values) => {
|
|
329
|
+
if (typeof rule !== "object" || !("each" in rule))
|
|
294
330
|
return;
|
|
331
|
+
const inner = "id" in rule ? rule.id : rule.value;
|
|
295
332
|
const entry = itemOf(nodeAt(node, rule.each), definitions);
|
|
296
|
-
const
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
333
|
+
const items = values.map((value) => {
|
|
334
|
+
const made = sample(entry && narrowed(entry, inner.split("."), value));
|
|
335
|
+
const item = isRaw(made) ? made : {};
|
|
336
|
+
put(item, inner, value, entry);
|
|
337
|
+
return item;
|
|
338
|
+
});
|
|
339
|
+
putList(row, rule.each, items, node);
|
|
300
340
|
};
|
|
301
341
|
const rows = {};
|
|
302
342
|
const changeAt = {};
|
|
@@ -316,12 +356,12 @@ export const crmManifestFake = (input, options) => {
|
|
|
316
356
|
externalId: String((index + 1) * 1000 + n + 1),
|
|
317
357
|
assignee: "7001",
|
|
318
358
|
...(pipeline ? { pipeline: pipeline.id, stage: pipeline.stages[n % pipeline.stages.length] } : {}),
|
|
319
|
-
...(money ? { amount: "100.50", currency:
|
|
359
|
+
...(money ? { amount: "100.50", currency: CURRENCY } : { amount: undefined, currency: undefined }),
|
|
320
360
|
...(pipeline && idAt("organization", n) ? { organization: idAt("organization", n) } : {}),
|
|
321
361
|
});
|
|
322
362
|
const person = idAt("person", n);
|
|
323
363
|
if (pipeline && person)
|
|
324
|
-
|
|
364
|
+
putEach(row, map.people, node, [person]);
|
|
325
365
|
if (keyset)
|
|
326
366
|
put(row, keyset, time, node);
|
|
327
367
|
return row;
|
|
@@ -384,7 +424,111 @@ export const crmManifestFake = (input, options) => {
|
|
|
384
424
|
}
|
|
385
425
|
if (manifest.users)
|
|
386
426
|
routes.push({ call: manifest.users.call, rows: () => users });
|
|
427
|
+
for (const kind of manifest.kinds) {
|
|
428
|
+
const spec = manifest.writes?.[kind];
|
|
429
|
+
if (!spec)
|
|
430
|
+
continue;
|
|
431
|
+
for (const verb of ["create", "update", "remove"]) {
|
|
432
|
+
const call = spec[verb];
|
|
433
|
+
if (!call)
|
|
434
|
+
continue;
|
|
435
|
+
const id = placeOf(call, "{id}");
|
|
436
|
+
const values = placeOf(call, "{values}");
|
|
437
|
+
routes.push({
|
|
438
|
+
call,
|
|
439
|
+
kind,
|
|
440
|
+
rows: () => rows[kind] ?? [],
|
|
441
|
+
write: { verb, spec, ...(id ? { id } : {}), ...(values ? { values } : {}) },
|
|
442
|
+
});
|
|
443
|
+
}
|
|
444
|
+
const currency = spec.fields.currency;
|
|
445
|
+
if (typeof currency === "object" && "fixed" in currency)
|
|
446
|
+
routes.push({ call: currency.fixed, rows: () => [], fixed: currency.at });
|
|
447
|
+
}
|
|
387
448
|
const denied = new Map();
|
|
449
|
+
let writes = 0;
|
|
450
|
+
let made = 0;
|
|
451
|
+
let lose = false;
|
|
452
|
+
/** A record, in the names a read maps, as a row the read maps back: what it does not name stays out. */
|
|
453
|
+
const rowFor = (kind, fields) => {
|
|
454
|
+
const entity = manifest.entities[kind];
|
|
455
|
+
const map = entity.map;
|
|
456
|
+
const node = rowNodeOf(entity.list);
|
|
457
|
+
const scalar = (field, value) => {
|
|
458
|
+
if (typeof value === "number" && FIELDS[kind][field] === "epoch")
|
|
459
|
+
return { ms: value };
|
|
460
|
+
return ["string", "number", "boolean"].includes(typeof value) ? value : undefined;
|
|
461
|
+
};
|
|
462
|
+
const given = Object.fromEntries(Object.keys(map).flatMap((field) => {
|
|
463
|
+
const value = scalar(field, fields[field]);
|
|
464
|
+
return value === undefined ? [] : [[field, value]];
|
|
465
|
+
}));
|
|
466
|
+
// Only the rules with a value shape the sample: one without would sample a value where the record has none.
|
|
467
|
+
const rules = Object.fromEntries(Object.entries(map).filter(([field]) => field in given || field === "pipeline"));
|
|
468
|
+
const row = rowOf(node, rules, FIELDS[kind], 0, given);
|
|
469
|
+
for (const [field, value] of Object.entries(fields)) {
|
|
470
|
+
if (!Array.isArray(value))
|
|
471
|
+
continue;
|
|
472
|
+
const ids = value.map((one) => (isRaw(one) ? String(one.externalId) : String(one)));
|
|
473
|
+
const rule = map[field];
|
|
474
|
+
const path = pathOf(rule);
|
|
475
|
+
if (typeof rule === "object" && "each" in rule)
|
|
476
|
+
putEach(row, rule, node, ids);
|
|
477
|
+
else if (path !== undefined && ids[0] !== undefined)
|
|
478
|
+
put(row, path, ids[0], node);
|
|
479
|
+
}
|
|
480
|
+
return row;
|
|
481
|
+
};
|
|
482
|
+
/** A create, update or remove of one record, as the service would make it, answered as its schema says. */
|
|
483
|
+
const written = (route, call) => {
|
|
484
|
+
writes += 1;
|
|
485
|
+
const { kind, write } = route;
|
|
486
|
+
const list = rows[kind] ?? [];
|
|
487
|
+
rows[kind] = list;
|
|
488
|
+
const root = rootOf(route.call);
|
|
489
|
+
const sampled = sample(root);
|
|
490
|
+
const answer = isRaw(sampled) ? sampled : {};
|
|
491
|
+
const externalId = write.verb === "create"
|
|
492
|
+
? String((manifest.kinds.indexOf(kind) + 1) * 1000 + 500 + ++made)
|
|
493
|
+
: String(readPlace(call, write.id) ?? "");
|
|
494
|
+
const place = list.findIndex((one) => idOf(kind, one) === externalId);
|
|
495
|
+
if (write.verb !== "create" && place < 0)
|
|
496
|
+
return refuse(`${call.operation}: no ${kind} ${externalId} in the fake`, 404);
|
|
497
|
+
if (write.verb === "remove") {
|
|
498
|
+
list.splice(place, 1);
|
|
499
|
+
return { body: answer };
|
|
500
|
+
}
|
|
501
|
+
const entity = manifest.entities[kind];
|
|
502
|
+
const before = place < 0 ? {} : (mapRecord(kind, entity, list[place]) ?? {});
|
|
503
|
+
const values = write.values ? readPlace(call, write.values) : undefined;
|
|
504
|
+
const known = [
|
|
505
|
+
...Object.values(write.spec.fields).flatMap((rule) => typeof rule === "object" && "to" in rule ? [rule.to] : []),
|
|
506
|
+
...(manifest.fields?.[kind] ? Array.from({ length: PAGE }, (_, n) => `${kind}_field_${n + 1}`) : []),
|
|
507
|
+
];
|
|
508
|
+
const unknown = Object.keys(isRaw(values) ? values : {}).filter((key) => !known.includes(key));
|
|
509
|
+
if (unknown.length)
|
|
510
|
+
return refuse(`${call.operation}: ${kind} has no field ${unknown.join(", ")} in the fake`);
|
|
511
|
+
const given = givenOf(write.spec, values);
|
|
512
|
+
const pipeline = pipelines.get(kind);
|
|
513
|
+
const fields = {
|
|
514
|
+
...(pipeline ? { pipeline: pipeline.id } : {}),
|
|
515
|
+
...before,
|
|
516
|
+
...given,
|
|
517
|
+
externalId,
|
|
518
|
+
updatedAt: Date.now(),
|
|
519
|
+
};
|
|
520
|
+
const currency = write.spec.fields.currency;
|
|
521
|
+
if (typeof currency === "object" && "fixed" in currency && fields.amount != null)
|
|
522
|
+
fields.currency = CURRENCY;
|
|
523
|
+
const row = rowFor(kind, fields);
|
|
524
|
+
if (place < 0)
|
|
525
|
+
list.push(row);
|
|
526
|
+
else
|
|
527
|
+
list[place] = row;
|
|
528
|
+
if (write.verb === "create" && write.spec.id)
|
|
529
|
+
putList(answer, write.spec.id, externalId, root);
|
|
530
|
+
return { body: answer };
|
|
531
|
+
};
|
|
388
532
|
const refuse = (message, status = 400) => {
|
|
389
533
|
own.push(message);
|
|
390
534
|
return { status, body: { message } };
|
|
@@ -464,6 +608,15 @@ export const crmManifestFake = (input, options) => {
|
|
|
464
608
|
const route = routeOf(call);
|
|
465
609
|
if (!route)
|
|
466
610
|
return refuse(`${call.operation ?? call.url.pathname}: no call of the source manifest is this one`, 404);
|
|
611
|
+
if (route.write && route.kind)
|
|
612
|
+
return written({ ...route, kind: route.kind, write: route.write }, call);
|
|
613
|
+
if (route.fixed !== undefined) {
|
|
614
|
+
const root = rootOf(route.call);
|
|
615
|
+
const sampled = sample(root);
|
|
616
|
+
const answer = isRaw(sampled) ? sampled : {};
|
|
617
|
+
putList(answer, route.fixed, CURRENCY, root);
|
|
618
|
+
return { body: answer };
|
|
619
|
+
}
|
|
467
620
|
const changes = route.since ? route : undefined;
|
|
468
621
|
if (changes?.since && readPlace(call, changes.since.place) === undefined)
|
|
469
622
|
return refuse(`${call.operation}: a read of changes without its since`);
|
|
@@ -514,7 +667,15 @@ export const crmManifestFake = (input, options) => {
|
|
|
514
667
|
answers: Object.fromEntries(api.operations.map((one) => [one.id, answerOf])),
|
|
515
668
|
});
|
|
516
669
|
return {
|
|
517
|
-
|
|
670
|
+
async fetch(input, init) {
|
|
671
|
+
const before = writes;
|
|
672
|
+
const answer = await fake.fetch(input, init);
|
|
673
|
+
if (lose && writes > before) {
|
|
674
|
+
lose = false;
|
|
675
|
+
throw new TypeError("fetch failed");
|
|
676
|
+
}
|
|
677
|
+
return answer;
|
|
678
|
+
},
|
|
518
679
|
calls: fake.calls,
|
|
519
680
|
get refusals() {
|
|
520
681
|
return [...fake.refusals, ...own];
|
|
@@ -533,6 +694,10 @@ export const crmManifestFake = (input, options) => {
|
|
|
533
694
|
if (timeOf(kind, row) === null)
|
|
534
695
|
throw new Error(`the fake cannot change the time of ${kind} ${id}`);
|
|
535
696
|
},
|
|
697
|
+
loseNextAnswer: () => {
|
|
698
|
+
lose = true;
|
|
699
|
+
},
|
|
700
|
+
requests: () => writes,
|
|
536
701
|
};
|
|
537
702
|
};
|
|
538
703
|
const externalIdOf = (manifest, kind, row) => {
|
|
@@ -616,3 +781,63 @@ export const crmManifestContract = (manifest, options) => {
|
|
|
616
781
|
},
|
|
617
782
|
}));
|
|
618
783
|
};
|
|
784
|
+
/**
|
|
785
|
+
* A `crmWriteContract` fixture for a writer built from a manifest's `writes`, over `crmManifestFake`: the writer, the
|
|
786
|
+
* first pipeline of the deal kind it writes, the service's own names of stage and owner, and the fake.
|
|
787
|
+
*/
|
|
788
|
+
export const crmManifestWriteFixture = async (manifest, options) => {
|
|
789
|
+
const fake = crmManifestFake(manifest, options);
|
|
790
|
+
const sending = {
|
|
791
|
+
manifest: options.api,
|
|
792
|
+
service: manifest.provider,
|
|
793
|
+
fetch: fake.fetch,
|
|
794
|
+
token: () => FAKE_MANIFEST_TOKEN,
|
|
795
|
+
...(options.baseUrl ? { baseUrl: options.baseUrl } : {}),
|
|
796
|
+
};
|
|
797
|
+
const source = crmSourceFromManifest(manifest, {
|
|
798
|
+
api: options.api,
|
|
799
|
+
call: serviceApiCall(sending),
|
|
800
|
+
...(options.hooks ? { hooks: options.hooks } : {}),
|
|
801
|
+
});
|
|
802
|
+
const writer = crmWriterFromManifest(manifest, {
|
|
803
|
+
api: options.api,
|
|
804
|
+
service: manifest.provider,
|
|
805
|
+
send: serviceApiSend(sending),
|
|
806
|
+
source: () => source,
|
|
807
|
+
});
|
|
808
|
+
const kind = DEAL_KINDS.find((one) => writer.capabilities.kinds.includes(one));
|
|
809
|
+
if (!kind)
|
|
810
|
+
throw new Error("the manifest writes no deal or lead, and the write contract needs one");
|
|
811
|
+
const [pipeline] = await source.pipelines(kind);
|
|
812
|
+
if (!pipeline)
|
|
813
|
+
throw new Error(`the fake holds no ${kind} pipeline`);
|
|
814
|
+
const fields = (manifest.writes?.[kind]?.fields ?? {});
|
|
815
|
+
const aliases = [fields.stage, fields.owner].flatMap((rule) => isRaw(rule) && typeof rule.to === "string" ? [rule.to] : []);
|
|
816
|
+
return {
|
|
817
|
+
writer,
|
|
818
|
+
kind,
|
|
819
|
+
pipeline,
|
|
820
|
+
aliases,
|
|
821
|
+
loseNextAnswer: fake.loseNextAnswer,
|
|
822
|
+
requests: fake.requests,
|
|
823
|
+
fake,
|
|
824
|
+
};
|
|
825
|
+
};
|
|
826
|
+
/** `crmWriteContract` over `crmManifestWriteFixture`, each case failing too when the fake refused a call. */
|
|
827
|
+
export const crmManifestWriteContract = (manifest, options) => {
|
|
828
|
+
const fakes = [];
|
|
829
|
+
return crmWriteContract(async () => {
|
|
830
|
+
const fixture = await crmManifestWriteFixture(manifest, options);
|
|
831
|
+
fakes.push(fixture.fake);
|
|
832
|
+
return fixture;
|
|
833
|
+
}).map(({ name, run }) => ({
|
|
834
|
+
name,
|
|
835
|
+
async run() {
|
|
836
|
+
fakes.length = 0;
|
|
837
|
+
await run();
|
|
838
|
+
const refused = fakes.flatMap((fake) => fake.refusals);
|
|
839
|
+
if (refused.length)
|
|
840
|
+
throw new Error(`the fake refused calls the writer made:\n${refused.join("\n")}`);
|
|
841
|
+
},
|
|
842
|
+
}));
|
|
843
|
+
};
|
package/dist/errors/reasons.d.ts
CHANGED
|
@@ -7,7 +7,7 @@ export declare const REASONS: ErrorReason[];
|
|
|
7
7
|
* Detail keys an error from this package may carry, until each is registered on its own reason. Not `cause`:
|
|
8
8
|
* that can hold a provider's or SQLite's raw text.
|
|
9
9
|
*/
|
|
10
|
-
export declare const DETAILS: readonly ["holders", "profile", "contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
|
|
10
|
+
export declare const DETAILS: readonly ["account", "holders", "profile", "contracts", "calendars", "allowed", "alternative", "arguments", "at", "available", "batch", "budget", "built", "candidates", "chat", "chat_id", "cli", "column", "complete", "emitted_bytes", "exact", "file", "forum", "guide", "hint", "id", "index", "kind", "limit", "limit_source", "line", "max_bytes", "model", "name", "operation_id", "operation_ids", "text_limit", "store_refused_in", "partial_output", "parent", "path", "permission", "person_ids", "previous_chat_id", "profiles", "provider_error", "provider", "recovery", "reference", "remembered", "retry_at", "retry_after_ms", "runtime", "saved", "scheduled_for", "script", "sent", "sent_count", "settlement_failed", "span", "sqlite", "stage", "standing", "state", "stderr", "term", "total", "upgraded", "wanted"];
|
|
11
11
|
/** What a CLI adds to the shared registry: its own reasons, and the detail keys its adapters raise. */
|
|
12
12
|
export interface AppErrors {
|
|
13
13
|
reasons?: readonly ErrorReason[];
|
package/dist/errors/reasons.js
CHANGED
|
@@ -50,6 +50,14 @@ const SIGN_IN = [
|
|
|
50
50
|
validation("profile.missing", "no profile named, and none is picked for the owner; details.profiles lists the ones here"),
|
|
51
51
|
["profile.unknown", "not_found", "no profile by this name on this computer; details.profiles lists the ones here"],
|
|
52
52
|
["account-remove.busy", "conflict", "a serve or a sync runs for this profile; stop it first"],
|
|
53
|
+
["account-remove.account-shared", "conflict", "another profile reads the same account, whose copy the store shares"],
|
|
54
|
+
["session.duplicate", "conflict", "another profile here already signs in to this account as this user"],
|
|
55
|
+
[
|
|
56
|
+
"account-remove.account-unknown",
|
|
57
|
+
"conflict",
|
|
58
|
+
"which account another profile holds could not be read, so --delete-data waits",
|
|
59
|
+
],
|
|
60
|
+
validation("profile.reserved", "the profile name is a folder every CRM account shares; pick another"),
|
|
53
61
|
["account-remove.unconfirmed", "confirmation_required", "removing an account asks first; add --yes"],
|
|
54
62
|
["account-remove.path-outside", "configuration_error", "the tool named a path outside its own folders"],
|
|
55
63
|
[
|
|
@@ -629,6 +637,8 @@ const OTHERS = [
|
|
|
629
637
|
validation("identity.agent-unnamed", "an agent's link names the agent, and never as the owner"),
|
|
630
638
|
validation("identity.not-shared", "only a match on a shared mailbox can say the mailbox is a company's"),
|
|
631
639
|
["organization.not-found", "not_found", "no stored organization has that id"],
|
|
640
|
+
validation("organization.own", "the organization is one of your own companies and is never deleted"),
|
|
641
|
+
validation("organization.erase-blocked", "an invoice, order, subscription or a row the organization wrote still names it; change those first, nothing was deleted"),
|
|
632
642
|
validation("organization.unnamed", "a free mailbox names no company; name the organization or the company"),
|
|
633
643
|
validation("organization.ambiguous", "more than one organization matches; name the one meant as a reference"),
|
|
634
644
|
validation("identity.shared-phone", "more than six people share the phone number, so it proposes no one"),
|
|
@@ -766,6 +776,7 @@ export const REASONS = defineReasons([
|
|
|
766
776
|
* that can hold a provider's or SQLite's raw text.
|
|
767
777
|
*/
|
|
768
778
|
export const DETAILS = [
|
|
779
|
+
"account",
|
|
769
780
|
"holders",
|
|
770
781
|
"profile",
|
|
771
782
|
"contracts",
|
|
@@ -71,6 +71,13 @@ export const WIRECAT_TOOLS = [
|
|
|
71
71
|
package: "@wirecat/amo-cli",
|
|
72
72
|
does: "amoCRM and Kommo: deals, contacts and companies, searchable with your other WireCat data",
|
|
73
73
|
},
|
|
74
|
+
{
|
|
75
|
+
command: "attio",
|
|
76
|
+
appName: "attio-cli",
|
|
77
|
+
envPrefix: "WCATTIO",
|
|
78
|
+
package: "@wirecat/attio-cli",
|
|
79
|
+
does: "Attio CRM: deals, people and companies, searchable with your other WireCat data",
|
|
80
|
+
},
|
|
74
81
|
{
|
|
75
82
|
command: "pbx",
|
|
76
83
|
appName: "asterisk-cli",
|
|
@@ -24,7 +24,10 @@ export interface FileMirrorOptions {
|
|
|
24
24
|
dryRun?: boolean;
|
|
25
25
|
/** Lets a run delete this many files although the guard would stop it. */
|
|
26
26
|
allowDeletions?: number;
|
|
27
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Lets a run replace this many existing files, on either side, although the guard would stop it. An app with a
|
|
29
|
+
* `--replace` switch passes `Number.POSITIVE_INFINITY`.
|
|
30
|
+
*/
|
|
28
31
|
allowReplacements?: number;
|
|
29
32
|
/** Globs of paths the mirror leaves alone on both sides, as `excludedBy` reads them. */
|
|
30
33
|
exclude?: string[];
|
|
@@ -70,7 +73,7 @@ export interface MirrorHints {
|
|
|
70
73
|
sync: string;
|
|
71
74
|
/** How a sync allows deletions: `--allow-deletions <count>`. */
|
|
72
75
|
allowDeletions: string;
|
|
73
|
-
/** How a sync allows replacements: `--
|
|
76
|
+
/** How a sync allows replacements: `--allow-replacements <count>`. */
|
|
74
77
|
allowReplacements: string;
|
|
75
78
|
/** How to leave a folder out: `ydisk work mirrors update <id> --ignore <path>`. */
|
|
76
79
|
exclude: string;
|
|
@@ -14,12 +14,12 @@ export declare const metadataService: (deps: ServiceDeps) => {
|
|
|
14
14
|
dryRun?: boolean;
|
|
15
15
|
}) => Promise<{
|
|
16
16
|
items: ({
|
|
17
|
+
error?: undefined;
|
|
17
18
|
chatId: string;
|
|
18
19
|
tags: import("../domain/channel-tags.js").ChannelTagMatch[];
|
|
19
20
|
algorithm: string;
|
|
20
21
|
fetchedAt: string | null;
|
|
21
22
|
source: string;
|
|
22
|
-
error?: undefined;
|
|
23
23
|
} | {
|
|
24
24
|
tags?: undefined;
|
|
25
25
|
algorithm?: undefined;
|
package/dist/store/index.d.ts
CHANGED
|
@@ -85,6 +85,7 @@ export { type NearestNote, NOTE_FIELDS, type NoteChunkToEmbed, type NoteHit, typ
|
|
|
85
85
|
export type { FileNoteInput, Link, LinkInput, LinkListFilter, Note, NoteFolder, NotesStore, NoteTag, } from "./sqlite/notes.js";
|
|
86
86
|
export type { Order, OrderDetail, OrderFilter, OrderInput, OrdersStore } from "./sqlite/orders.js";
|
|
87
87
|
export type { OrganizationFilter } from "./sqlite/organization-categories.js";
|
|
88
|
+
export type { OrganizationErasure } from "./sqlite/organization-erase.js";
|
|
88
89
|
export { DEFAULT_OWNER_LANGUAGES, ownerLanguages } from "./sqlite/owner-languages.js";
|
|
89
90
|
export { type ListedPerson, PEOPLE_SORTS, type PeopleList, type PeopleListOptions, type PeopleSort, type SimilarPerson, } from "./sqlite/people-list.js";
|
|
90
91
|
export { DOUBT_REASONS, type DoubtIdentity, type DoubtMove, type DoubtReason, type KeptPerson, type PersonDoubt, type PersonDoubts, type TestDataPerson, } from "./sqlite/person-doubts.js";
|
|
@@ -3,6 +3,7 @@ import { calendarCursorKey, calendarWritesOver } from "./calendar.js";
|
|
|
3
3
|
import { forgetCalendarRows } from "./calendar-forget.js";
|
|
4
4
|
import { eq, inArray, sql } from "./drizzle/core.js";
|
|
5
5
|
import { forgetDanglingEvidence, forgetEvidenceTo } from "./evidence-signature.js";
|
|
6
|
+
import { eraseImportedOrganizations, importedOrganizations } from "./organization-erase.js";
|
|
6
7
|
import { eraseImportedPeople, importedPeople } from "./person-erase.js";
|
|
7
8
|
import { accountIdentities, accounts, aliases, botUpdates, chatEventPeople, chatEvents, chatMembers, chats, chunks, fetchLeases, involvements, memberCounts, memberObservationMembers, memberObservations, memberStays, messageReactions, messageRevisions, messages, messageTranscripts, pollVotes, projects, syncCursors, syncRanges, syncs, } from "./schema.js";
|
|
8
9
|
import { dropUnusedVectors } from "./vector-index.js";
|
|
@@ -11,6 +12,7 @@ export const purgeAccount = (context, accountKey) => {
|
|
|
11
12
|
const { orm, database, now } = context;
|
|
12
13
|
const unseenBefore = unreferenced(database, "identities");
|
|
13
14
|
const imported = importedPeople(database, accountKey);
|
|
15
|
+
const importedCompanies = importedOrganizations(database, accountKey);
|
|
14
16
|
const at = now();
|
|
15
17
|
const meetingIds = "SELECT id FROM meetings WHERE account_id = ?";
|
|
16
18
|
const transcriptIds = `SELECT id FROM meeting_transcripts WHERE meeting_id IN (${meetingIds})`;
|
|
@@ -114,6 +116,7 @@ export const purgeAccount = (context, accountKey) => {
|
|
|
114
116
|
orm.delete(accounts).where(eq(accounts.id, accountKey)).run();
|
|
115
117
|
dropOrphanPeople(database, unseenBefore);
|
|
116
118
|
eraseImportedPeople(context, imported);
|
|
119
|
+
eraseImportedOrganizations(context, importedCompanies);
|
|
117
120
|
forgetDanglingEvidence(database, at);
|
|
118
121
|
dropUnusedVectors(database, hashes);
|
|
119
122
|
// The links' delete trigger writes a revision naming the account it is purging; the history goes with the links.
|
|
@@ -7,6 +7,7 @@ export const STAGE_ENTRY_DAYS = 90;
|
|
|
7
7
|
/** A stage entered longer ago than this opens no task: the copy missed the deal for more than a sync or two. */
|
|
8
8
|
const STAGE_TASK_DAYS = 7;
|
|
9
9
|
const DAY = 86_400_000;
|
|
10
|
+
const SECOND = 1000;
|
|
10
11
|
/**
|
|
11
12
|
* Every stage entry of the kind's rows in one pipeline, or of one row, oldest first per row: the CRM's own history
|
|
12
13
|
* where a row has any, else the copy's diffs, never both for one row. Entries handled or expired stay history.
|
|
@@ -79,6 +80,8 @@ export const crmStageEntriesOver = (context) => {
|
|
|
79
80
|
const accountId = findAccountPk(context, key);
|
|
80
81
|
if (accountId === undefined)
|
|
81
82
|
return [];
|
|
83
|
+
// A CRM's history keeps whole seconds: a move in the second the rules were set would read as made before them.
|
|
84
|
+
const from = Math.max(Math.floor(since / SECOND) * SECOND, at - STAGE_TASK_DAYS * DAY);
|
|
82
85
|
return database
|
|
83
86
|
.prepare("SELECT r.id, r.external_id, json_extract(r.fields, '$.kind') AS kind, coalesce(d.id, l.id) AS item_id, " +
|
|
84
87
|
"s.external_id AS stage, s.name AS stage_name, p.name AS pipeline_name FROM records r " +
|
|
@@ -91,7 +94,7 @@ export const crmStageEntriesOver = (context) => {
|
|
|
91
94
|
"WHERE r.account_id = ? AND r.type = ? AND r.deleted_at IS NULL AND coalesce(d.id, l.id) IS NOT NULL " +
|
|
92
95
|
"AND json_extract(r.fields, '$.handled') IS NULL AND json_extract(r.fields, '$.at') >= ? " +
|
|
93
96
|
"ORDER BY json_extract(r.fields, '$.at'), r.id")
|
|
94
|
-
.all(accountId, STAGE_ENTRY_RECORD,
|
|
97
|
+
.all(accountId, STAGE_ENTRY_RECORD, from)
|
|
95
98
|
.map((row) => {
|
|
96
99
|
const ref = `${String(row.kind)}:${String(row.item_id)}`;
|
|
97
100
|
return {
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
import type { CacheDatabase } from "../driver.js";
|
|
2
|
+
export declare const count: (database: CacheDatabase, sql: string, ...params: (string | number)[]) => number;
|
|
3
|
+
/**
|
|
4
|
+
* What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
|
|
5
|
+
* foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
|
|
6
|
+
* goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
|
|
7
|
+
*/
|
|
8
|
+
export declare class ErasePlan {
|
|
9
|
+
#private;
|
|
10
|
+
private readonly database;
|
|
11
|
+
readonly deleted: Record<string, number>;
|
|
12
|
+
readonly detached: Record<string, number>;
|
|
13
|
+
readonly blocked: string[];
|
|
14
|
+
constructor(database: CacheDatabase);
|
|
15
|
+
pointers(type: string, among: string, params: (string | number)[]): this;
|
|
16
|
+
/** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
|
|
17
|
+
foreignKeys(target: string, id: number, own: ReadonlySet<string>): this;
|
|
18
|
+
run(): void;
|
|
19
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { pointerPairs } from "./entity-types.js";
|
|
2
|
+
/** Who wrote or approved a row: the row is the writer's history, never silently rewritten. */
|
|
3
|
+
const AUTHORS = new Set(["author", "confirmed_by", "decided_by", "proposed_by", "actor", "closed_by"]);
|
|
4
|
+
/** A link is about both ends: one that loses an end means nothing, so it goes. */
|
|
5
|
+
const LINK_ROWS = new Set(["links", "mentions", "task_assignments"]);
|
|
6
|
+
const hasChildren = (database, table) => database
|
|
7
|
+
.prepare(`SELECT 1 FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f WHERE m.type = 'table' AND f."table" = ?
|
|
8
|
+
LIMIT 1`)
|
|
9
|
+
.get(table) !== undefined;
|
|
10
|
+
const nullable = (database, table, column) => Number(database.prepare(`SELECT "notnull" AS n FROM pragma_table_info('${table}') WHERE name = ?`).get(column)?.n) ===
|
|
11
|
+
0;
|
|
12
|
+
export const count = (database, sql, ...params) => Number(database.prepare(`SELECT count(*) AS n FROM ${sql}`).get(...params)?.n);
|
|
13
|
+
/**
|
|
14
|
+
* What deleting an entity does to the rows that name it, read from the store's own `*_type`/`*_id` pointers and
|
|
15
|
+
* foreign keys, so the plan shown and the delete run read one list. A row that only ties something to the entity
|
|
16
|
+
* goes; one that can be without it loses the pointer; one that cannot, or that the entity wrote, blocks the delete.
|
|
17
|
+
*/
|
|
18
|
+
export class ErasePlan {
|
|
19
|
+
database;
|
|
20
|
+
deleted = {};
|
|
21
|
+
detached = {};
|
|
22
|
+
blocked = [];
|
|
23
|
+
#steps = [];
|
|
24
|
+
constructor(database) {
|
|
25
|
+
this.database = database;
|
|
26
|
+
}
|
|
27
|
+
pointers(type, among, params) {
|
|
28
|
+
for (const { table, pointer } of pointerPairs(this.database)) {
|
|
29
|
+
const where = `${pointer}_type = '${type}' AND ${pointer}_id IN (${among})`;
|
|
30
|
+
const n = count(this.database, `"${table}" WHERE ${where}`, ...params);
|
|
31
|
+
if (n === 0)
|
|
32
|
+
continue;
|
|
33
|
+
const key = `${table}.${pointer}`;
|
|
34
|
+
if (LINK_ROWS.has(table) || !nullable(this.database, table, `${pointer}_id`)) {
|
|
35
|
+
if (!LINK_ROWS.has(table) && (AUTHORS.has(pointer) || hasChildren(this.database, table))) {
|
|
36
|
+
this.blocked.push(`${n} ${table} (${pointer})`);
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
this.#add(this.deleted, key, n, `DELETE FROM "${table}" WHERE ${where}`, params);
|
|
40
|
+
}
|
|
41
|
+
else
|
|
42
|
+
this.#add(this.detached, key, n, `UPDATE "${table}" SET ${pointer}_type = NULL, ${pointer}_id = NULL WHERE ${where}`, params);
|
|
43
|
+
}
|
|
44
|
+
return this;
|
|
45
|
+
}
|
|
46
|
+
/** Foreign keys to `target`, but those in `own`, which the caller deletes with the entity. */
|
|
47
|
+
foreignKeys(target, id, own) {
|
|
48
|
+
for (const row of this.database
|
|
49
|
+
.prepare(`SELECT m.name AS tbl, f."from" AS col FROM sqlite_master m JOIN pragma_foreign_key_list(m.name) f
|
|
50
|
+
WHERE m.type = 'table' AND f."table" = ?`)
|
|
51
|
+
.all(target)) {
|
|
52
|
+
const table = String(row.tbl);
|
|
53
|
+
const column = String(row.col);
|
|
54
|
+
if (own.has(table))
|
|
55
|
+
continue;
|
|
56
|
+
const n = count(this.database, `"${table}" WHERE "${column}" = ?`, id);
|
|
57
|
+
if (n === 0)
|
|
58
|
+
continue;
|
|
59
|
+
if (nullable(this.database, table, column))
|
|
60
|
+
this.#add(this.detached, `${table}.${column}`, n, `UPDATE "${table}" SET "${column}" = NULL WHERE "${column}" = ?`, [id]);
|
|
61
|
+
else
|
|
62
|
+
this.blocked.push(`${n} ${table} (${column})`);
|
|
63
|
+
}
|
|
64
|
+
return this;
|
|
65
|
+
}
|
|
66
|
+
run() {
|
|
67
|
+
for (const step of this.#steps)
|
|
68
|
+
step();
|
|
69
|
+
}
|
|
70
|
+
#add(into, key, n, sql, params) {
|
|
71
|
+
into[key] = (into[key] ?? 0) + n;
|
|
72
|
+
this.#steps.push(() => this.database.prepare(sql).run(...params));
|
|
73
|
+
}
|
|
74
|
+
}
|